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
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
.
No you can't override the functionality of HomeButton. Its for security reasons so that malicious apps does not take control of your home button.
If you want to handle home button inplement home screen.
I am not sure if the below is helpfull.
You can Override onUserLeaveHint
protected void onUserLeaveHint ()
if you want to
Added in API level 3Called as part of the activity lifecycle when an activity is about to go into the background as the result of user choice. For example, when the user presses the Home key, onUserLeaveHint() will be called, but when an incoming phone call causes the in-call Activity to be automatically brought to the foreground, onUserLeaveHint() will not be called on the activity being interrupted. In cases when it is invoked, this method is called right before the activity's onPause() callback. This callback and onUserInteraction() are intended to help activities manage status bar notifications intelligently; specifically, for helping activities determine the proper time to cancel a notfication.
Try to override this method and write your code.
@Override
protected void onStop()
{
super.onStop();
startActivity(new Intent(this, ActivityB.class));
}
来源:https://stackoverflow.com/questions/18380663/overriding-the-functionality-of-home-button