How to override the Home key function

2019-09-08 09:25发布

I'm developing a pattern lock app.
The problem is that when the phone screen is off, then my LockActivity shows to be unlocked, but when i press the mobile home key, then it works.

I want to override the home key function (as it's not working) until I enter the unlock pattern.

 @Override
  public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {

        if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)||(keyCode == KeyEvent.KEYCODE_POWER)||(keyCode == KeyEvent.KEYCODE_VOLUME_UP)||(keyCode == KeyEvent.KEYCODE_CAMERA)) {

            return true; 
        }
       if((keyCode == KeyEvent.KEYCODE_HOME)){

           return true;
        }

    return false;

    }

    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_POWER ||(event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN)||(event.getKeyCode() == KeyEvent.KEYCODE_POWER)) {
            //Intent i = new Intent(this, NewActivity.class);
            //startActivity(i);
            return false;
        }
         if((event.getKeyCode() == KeyEvent.KEYCODE_HOME)){


           return true;
         }
    return false;
    }

I googled, but did not get any solution.
Please help me.

1条回答
放我归山
2楼-- · 2019-09-08 09:39

There is no way to override the Home key as such. There is no way to check for the Home key pressed event as well. The only possibility you have is, to write your own Home or Launcher activity. To do so implement your activity, and register it as follows in the Manifest:

<activity
    android:name=".MyNewHomeActivity"
    android:launchMode="singleInstance">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.HOME" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
</activity>

Once you have done this you can decide what to do in onCreate() or onResume(). Note that this requires your app/activity to be the default launcher.

查看更多
登录 后发表回答