Search code examples
androidpower-managementwakelock

How to keep android device from sleeping while plugged in


I'd like to keep the screen on whenever one of my Activities are running and the phone is plugged in to a power source. I know that Wakelocks are tricky, so I'm looking for an example or some documentation on how to accomplish this specific goal.


Solution

  • Don't use wake locks for this -- just set and clear the window flag WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON based on whether the device is currently plugged in. You can set the flag with Activity.getWindow().addFlags().

    So the code would be

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);