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.
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.
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.