android+捕获home键方法

在Activity中接收按键事件方法是onKeyDown(int keyCode,KeyEvent event),而松开按键是onKeyUp方法。

@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
 
            case KeyEvent.KEYCODE_FOCUS:
   Log.i(TAG, "doSnap: KeyEvent.KEYCODE_FOCUS");
                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
                    doFocus(true);
                }
                return true;
            case KeyEvent.KEYCODE_CAMERA:
  Log.i(TAG, "doSnap: KeyEvent.KEYCODE_CAMERA");
                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
                    doSnap();
                }
                return true;
            case KeyEvent.KEYCODE_DPAD_CENTER:
  Log.i(TAG, "doSnap:KeyEvent.KEYCODE_DPAD_CENTER");
                // If we get a dpad center event without any focused view, move
                // the focus to the shutter button and press it.
                if (mFirstTimeInitialized && event.getRepeatCount() == 0) {
                    // Start auto-focus immediately to reduce shutter lag. After
                    // the shutter button gets the focus, doFocus() will be
                    // called again but it is fine.
                    if (mHeadUpDisplay.collapse()) return true;
                    doFocus(true);
                    if (mShutterButton.isInTouchMode()) {
                        mShutterButton.requestFocusFromTouch();
                    } else {
                        mShutterButton.requestFocus();
                    }
                    mShutterButton.setPressed(true);
                }
                return true;
       case KeyEvent.KEYCODE_BACK:
  Log.i(TAG, "KeyEvent.KEYCODE_BACK");
  if(mCameraDevice!=null){
          mCameraDevice.sendCommand(CAMERA_CMD_FRONT_CAMERA, 0, 0); 
          mCameraDevice.sendCommand(CAMERA_CMD_BACK_CAMERA, 0, 0);
          finish();
  }
  return true;
       case KeyEvent.KEYCODE_HOME:
  Log.i(TAG, "KeyEvent.KEYCODE_HOME");
  if(mCameraDevice!=null){
          mCameraDevice.sendCommand(CAMERA_CMD_FRONT_CAMERA, 0, 0); 
          mCameraDevice.sendCommand(CAMERA_CMD_BACK_CAMERA, 0, 0);
          finish();
  }
  return true;
        }

return super.onKeyDown(keyCode, event);
    }

在按键中KeyEvent.KEYCODE_BACK返回键是可以直接监听的,但Home键是在framework监听,那么监听Home的方法就是:

第一:在Activity中加入,重写onAttachedToWindow,以实现屏蔽Home键.

@Override
    public void onAttachedToWindow() {
        this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
        super.onAttachedToWindow();
    }

第二在按键监听中加入Home键处理代码。

你可能感兴趣的:(android)