Share the post "How To Override Back & Home Button In An Android App"
To override the back button in an Android app, you just need to capture when the user presses the back button by overriding the onKeyDown() method and onBackPressed() methods. For the home button, the onUserLeaveHint() method gets always called.
These methods belong to the Activity class and must be overriden in order for your app to do what you intend it to do. One of the Android developers actually posted an article on the best way to ensure that your code will work across all versions of the Android platform whether old or new.
Check out the codes below.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR && keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) { onBackPressed(); } return super.onKeyDown(keyCode, event); } @Override public void onBackPressed() { // do what you want here return; } |
Okay, so the above methods are for capturing when the user presses the back button. What about the home button? The answer is, there is no way. This is by design because the home button is the user’s only means of escape in case some malware app that you just opened threatens to harm your phone.
However, I did find a hack that can detect when the home button is pressed by checking the tasks of the ActivityManager. I noticed that whenever the home button is pressed, my app’s Activity is always second in the list so that is my basis in determining it. This could also apply if there is an incoming phone call although I have not tested this. Let me know if this works too.
Check out the code below.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@Override protected void onUserLeaveHint() { super.onUserLeaveHint(); exitAppAnimate(); } private void exitAppAnimate() { ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> recentTasks = activityManager.getRunningTasks(Integer.MAX_VALUE); for (int i=0; i<recentTasks.size(); i++) { if (i == 1 && recentTasks.get(i).baseActivity.toShortString().indexOf(getPackageName()) > -1) { // home button pressed break; } } } |
It is worth noting that the index position of the Activity may be different with how your app starts an activity. You can check the output in the loop to see which index your Activity class falls under.
|
1 |
System.out.println("Application executed : " +recentTasks.get(i).baseActivity.toShortString()+ "\t\t ID: "+recentTasks.get(i).id+""); |