Search code examples
androidandroid-serviceandroid-broadcast

Android: prevent device from locking when pressing the power button


I have an app which when the device locks it starts an activity instead. By doing this the device doesn't lock but it shows an activity. This is OK. My problem is that if I am already in the activity and when I press the power button the device locks.

In the BroadcastReceiver I can see the screen is off:

if (action.equals(Intent.ACTION_SCREEN_OFF)) {
            isScreenOff = true;
            final Intent serviceIntent = new Intent(context, Screensaver.class);
            serviceIntent.putExtra("screen_state", isScreenOff);
            context.startService(serviceIntent);
            Log.i(TAG, "SCREEN OFF.");
        }

Then the onStartCommand() in my service is called. In it I start the activity. In the activity I see that the onResume() is called and then onPause() and that's it. The device is locked and the screen is off. If I unlock it manually, the activity is there, but it shouldn't be necessary to unlock it manually. Do you have any idea how I can fix that? (Do not hesitate to ask me if I need to post more code).

EDIT Here is a video to get it more clear. In the end of it I am in my screensaver activity and when I press the power button the device locks and does not starts the screen again.


Solution

  • I figured it out! Since the activity started when I lock the device, calling Activity.recreate() in onStop() fixed my problem.