Whenever a user presses the search button and the SearchView component is shown, it goes back to the button MenuItem once a query is submitted.

However, when a user press the Back key, only the keyboard is hidden but the SearchView component is still visible. If you press the Back key again, one would expect the SearchView to be iconified but the app exits instead.

The workaround for this is to add an OnFocusChangeListener to the SearchView component. Whenever the keyboard gets shown and hidden, the onFocusChange() method gets called.

Here is the code:

This is how to simulate a back key press event in Android programmatically. Do note that this is called twice to dispatch a key event for both UP and down actions.

If only one of these two is executed, it will not work so make sure both of these are executed.

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.

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.

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.

Related Posts Plugin for WordPress, Blogger...