Detect Home Button Press in Android

Detect HomeButton pressed Android before onBackPressed

I'm sorry to say but all the suggested answers are obsolete and some of them are downright wrong.

Intercepting HOME directly was blocked way back on Froyo due to security issues and a fear of malware (if you can intercept HOME you can try and hijack the device).

The only solution i'm aware of which seperates BACK from HOME is to to intercept the onNewIntent() event listener.

onNewIntent() is fired when an app is running, and receives another intent to be launched. That is why you will get it when HOME is pressed.

When BACK is pressed, your app is not going to receive an intent. All that happens is that the apps on top of yours are removed. So your app appears from the back stack with only onResume() being called.

So that is how you can tell.

It is also mentioned here.
Goodluck.

Lock Screen detect home button

            WindowManager windowManager  = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
}
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams.x = 0;
layoutParams.y = 0;
layoutParams.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
View window = LayoutInflater.from(this).inflate(R.layout.activity_main, null, false);

windowManager.addView(window, layoutParams);

The following piece of code blocks the home, back and recents button as per the requirement.

Also requires the following permission in the manifest:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />


Related Topics



Leave a reply



Submit