In , I discussed the pros and cons of the various means of keeping the screen alive in Android, focusing mainly on the need for sandbox permissions in your application’sAndroidManifest.xmlfile.
In this post, I’d like to further elaborate on the “shortcut” techniques to allow you to keep the screen alive, without explicitly managing a Wake Lock in your application.
FLAG_KEEP_SCREEN_ON
I’ve already covered the technique of setting a flag on your Activity’s main window to keep the screen active:
getWindow().addFlags( WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON );
There are two things to keep in mind with this approach:
- FLAG_KEEP_SCREEN_ONonly works when the app window is onscreen. If the user switches apps, Android automatically releases the wake lock. That might be fine for your use case, but if you have a long-running background task that really needs to keep the device running until finished, this isn’t an airtight approach.
- FLAG_KEEP_SCREEN_ONdoes just that; it keeps the screen active along with the rest of the device. If you directly create and manage a raw wake lock in your own code, you have more granularity, for example allowing the screen to go dim or go off completely whilst still allowing the CPU to do its thing.
I won’t discuss how to create and manage a Wake Lock directly; instead, I’ll refer you to the and to a short (I happen to like the site for its nice, short and useful code snippets).
android:keepScreenOn
Although I haven’t tried this in my own dev work, you can also enforce “screen always on” behavior on a per-view basis.
Every view has an that you can use to keep the screen active whenever the view is visible. This should be as easy as simply setting the attribute in the XML layout you use to define your views, plus it needs no Java code at all.
I suspectandroid:keepScreenOnworks by setting theFLAG_KEEP_SCREEN_ONon the window for you whenever the view is visible to the user. Anyway, this is handy to use if your need to keep the screen active is associated with a particular view in your app.