tags:

views:

465

answers:

2
+6  Q: 

Force Screen On

How do I force the screen to stay active and not shut off while my app is running?

+4  A: 
Michael Cramer
+14  A: 

PLEASE DO NOT USE A WAKE LOCK

This requires that you give your app an additional permission, and it is very easy to introduce bugs where you accidentally remain holding the wake lock and thus leave the screen on.

It is far, far better to use the window flag FLAG_KEEP_SCREEN_ON, which you can enable on your activity's window in your onCreate() like this:

    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

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

This will make sure that the screen stays on while your window is in the foreground, and only while it is in the foreground. It greatly simplifies this common use case, eliminating any juggling you need to do as your app transitions between states.

hackbod
Does that prevent the device from sleeping? If so, the commonness of WAKE_LOCK strikes me as a shocking mistake!
Michael Cramer
Yes it keeps the screen on and prevents the device from sleeping.
hackbod
Thanks!! great info
I am currently using a Wake Lock to make sure the device does not turn off while tracking with the GPS. When the user stops tracking I release the wake lock. If I use your suggestion above, is it possible to remove the flag after you add it. Would I need to redraw the window?
Yes you can remove the flag, with the appropriate window API. You don't need to worry about causing anything to be drawn, the framework does that if needed.
hackbod