As @j__m said, TYPE_KEYGUARD no longer supported. There are many other ways that were discussed on other issues, but do not work at the last level of the API. I will save your efforts and would like to share some of the searches, trial versions, and mistakes that I made. I tried many methods, but none of them worked for me in the level 17 API. I tried the answers to
Method call, when the home button is pressed on the android ,
Detect home button click on android and
Some of the ones I tried (including the answers above) and didn't work were:
Using keyCode==KeyEvent.KEYCODE_HOME is much of the above. Now, if you read the KeyEvent.KEYCODE_HOME documentation, he says This key is handled by the framework and is never delivered to applications . So it is no longer valid now.
I tried using onUserLeaveHint() . The documentation says: Called 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 .
If you do not invoke any actions from your current activity where you discover the home button, then you can be able to use this approach. The problem with this is that the method is also called when the Activity starts from within the action in which you call onUserleaveLint() , as in my case. See Android onBackPressed / onUserLeaveHint for details . Therefore, he is not sure that he will call ONLY by pressing the home button.
Finally, executed for me:
Having seen How to check the running applications in Android? , you can say that if your recent task was shown with a long press of the "home" button, it was sent to the background (for example, the "Home" button was pressed).
So, in your onPause() activity, in which you are trying to find the home button, you can check if the application has been sent to the background.
@Override public void onPause() { if (isApplicationSentToBackground(this)){
Function to check if your application that was recently sent to the background was:
public boolean isApplicationSentToBackground(final Context context) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<RunningTaskInfo> tasks = am.getRunningTasks(1); if (!tasks.isEmpty()) { ComponentName topActivity = tasks.get(0).topActivity; if (!topActivity.getPackageName().equals(context.getPackageName())) { return true; } } return false; }
Using this, I was able to successfully detect a Home Button click. Hope this works for you too.