Search code examples
androidfullscreenwakelock

Allow screen to turn off for fullscreen android app


I have tried several published solutions to try and turn the screen off in android, including:

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

Which results in no change.

WindowManager.LayoutParams param = getWindow().getAttributes();
param.screenBrightness = 0;
param.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
getWindow().setAttributes(param);

Which results in a slightly dimmed screen (on Android 4.2.1)

//Release all previously held WakeLocks
if (mWakeLock.isHeld()) {
    mWakeLock.release();
}
//Then acquire a partial wake lock (which should allow the display to turn off)
PowerManager powerMan = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
mWakeLock = powerMan.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Partial WakeLock");
mWakeLock.acquire();

Which results in no change.

And finally, the illegal

PowerManager powerMan = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
powerMan.goToSleep(1000);

which clearly doesn't work because:

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

is not permissible (to non-system apps).

I am assuming these problems are because my app is android:theme="@style/FullscreenTheme".

Are there any workable solutions to allow a fullscreen app to go to sleep without sacrificing the wonderful fullscreen theme?


Solution

  • After writing a simple answer to try and post to @CommonsWare, I found that the problem didn't persist.

    I combed through my code several times, and still didn't find anything which would cause the screen to stay awake. I rewrote the entire app from scratch (always a good exercise, ending up with much cleaner logic), and the problem disappeared.

    Lesson learnt - if all else fails, re-write everything again. It's a useful exercise in itself :)