Lock Screen detect home button

With Device admin permission https://developer.android.com/guide/topics/admin/device-admin you can pragmatically lock unlock device.

That app also use permission for "retrieve running apps" android.permission.GET_TASKS, so with that we can detect current foreground running app. check answer. https://stackoverflow.com/a/17756786/1025070 with that if user try to press home and leave we can instant check app is not in forground, and relaunch our activity again. (its workaround to detect if user leave from app with Home press).

Check my app https://play.google.com/store/apps/details?id=com.udayalakmal.applock&hl=en that add overlay of lockscreen on any app that can not bypass. use same check foreground running app.


@user2511882 - Created sample app that simply load Activity when device locked, and another activity when device unlock

https://github.com/UdayaLakmal/LockScreenDemo

**This is only a demo, you have to use receivers with background service for continue monitor device lock state and handle memory leaks, .Tested with Android 6 API 23 no need to monitor running apps since this only use with device lock screen.

**Check how I get Home button press event in Lockscreen activity.


            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" />