androidandroid-screenandroid-screen-support

How to prevent automatic screen lock on android by code?


In my app there is a long loading process, and if the devices puts on the screen lock, my process stops for some reason.

How can i prevent the device from automatic screen lock?


Solution

  • you have to declare this uses-permission on AndroidManifest:

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

    And in your code Activity:

    PowerManager powerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
    WakeLock wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");
    wakeLock.acquire();
    

    Just remember to release this lock when your application is paused or destroyed by doing this:

    wakeLock.release();
    

    Usually, it's suggested to call the acquire method inside the onResume() of your activity and the release method in onPause(). This way we guarantee that our application still performs well in the case of being paused or resumed.