Search code examples
javaandroidhome-button

Overriding the functionality of Home Button


In android I have been able to override the functionality of back button very easily but for my app I need to override the home button. For example the user is in Activity A, when he presses the home button, activity B is launched. I have tried to do the following but it failed.

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

    if(keyCode == KeyEvent.KEYCODE_HOME)
    {
        startActivity(new Intent(this, ActivityB.class));

        return true;
    }
    return super.onKeyDown(keyCode, event);
}

I am sure it can be done because in Nova Launcher when the user is on home screen and he presses the home button, the launcher offers the user a list of home screens to jump to. I need same kind of functionality. How can this be achieved.

Regards


Solution

  • Try this:

    @Override
        protected void onUserLeaveHint() {
            if (!navigating) {
                Intent intent2 = new Intent();
                intent2.setClass(ActivityA.this, ActivityB.class);
                intent2.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                forceHome(this, intent2);
            }
            super.onUserLeaveHint();
        }
    
    public static void forceHome(Context paramContext, Intent paramIntent) {
    
            if (paramIntent != null) {
                ((AlarmManager) paramContext.getSystemService(ALARM)).set(1,
                        System.currentTimeMillis(),
                        PendingIntent.getActivity(paramContext, 0, paramIntent, 0));
            }
    
        }
    

    As a security feature of android, the activity only launches after 5 seconds. If you want to launch it immediately. use your own Home Launcher.