LoginSignup
6
0

More than 5 years have passed since last update.

Androidアプリで音量キーを使ったロックパターンを作ってみた。Fragment編

Last updated at Posted at 2017-11-02

音量ボタンを使って、5秒以内にコマンドを打ち込むとロックが解除されるコードを書きました。

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {

    //音量変更時のコマンドの初期化
    mCommandTime = 0;
    mSuccessCommand = "";

    final View v = inflater.inflate(R.layout.fragment_recording, container, false);

    v.setOnKeyListener(new View.OnKeyListener() {
      @Override
      public boolean onKey(View v, int keyCode, KeyEvent event) {


        if (mCommandTime==0) {
          //一回押されたら5秒後にmCommandTimeが0にリセットされるまではtimerが起動しない
          mCommandTime++;

          final Handler handler = new Handler();
          handler.postDelayed(new Runnable() {
            @Override
            public void run() {
              Log.d(TAG, "5秒経ったからopenPassを初期化");
              mSuccessCommand = "";
              //タイマーがonの時だけ値を文字列(mSuccessCommand)に追加できる
              Log.d(TAG, "5秒経過したからtimerを起動できる");
              mCommandTime= 0;
            }
          }, 5000);

        }else{
          Log.d(TAG,"comandTimeが"+mCommandTime+"で、5秒をすぎてるからtimerは使えない");
        }

        if(event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP){
          mSuccessCommand=mSuccessCommand+"1";
          Log.d(TAG,"Commandに+1、今のcommandは"+mSuccessCommand);


        }else if(event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN){
          mSuccessCommand=mSuccessCommand+"0";
          Log.d(TAG,"Commandに+0、今のcommandは"+mSuccessCommand);

        }

        if (mSuccessCommand.equals("01101")) { 
          Log.i(TAG,"life コマンドが解除された");

          Toast.makeText(getActivity(), "ロックが解除されました。", Toast.LENGTH_SHORT).show();

          //ここでロック解除時の処理をする
      }
    });
    // View#setFocusableInTouchModeでtrueをセットしておくこと、重要
    v.setFocusableInTouchMode(true);
    return v;
  }
}

ここには書いてないんですが、KeyEventは「Down」と「Up」の2回呼ばれるので、「Down」の時だけ入るif文とかを作るといいです。

個人的には、

今後SNSとかを作ってく中で、音量ボタンのロック解除でアプリの透明具合とか調整したいなーって思ってます。楽しそー

6
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
0