3

I created a new project with target API 15 (ICS) with empty Activity. I added permission to manifest:

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

I added code to onCreate():

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        PowerManager pm = (PowerManager) getSystemService(getApplicationContext().POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Tag");
        wl.acquire();

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

But nothing happens with the device. According to PowerManager documentation I expected the screen to go off (immediately). So, am I doing something wrong or is this not working?


EDIT:

I tried Ashish Ranjan's suggestion to manually set screenBrightness after acquiring WakeLock but this too does not work.

c0dehunter
  • 6,412
  • 16
  • 77
  • 139

2 Answers2

1

As per the Android documentation, using PARTIAL_WAKE_LOCK won't turn the screen off. But it will allow the screen to go off, when this mode is active in the WakeLock.

So, the device screen won't turn off instantly, you'll have to wait for the screen to timeout (which depends on the time set in the device display settings) but the CPU will keep running.

PARTIAL_WAKE_LOCK

Wake lock level: Ensures that the CPU is running; the screen and keyboard backlight will be allowed to go off.

If the user presses the power button, then the screen will be turned off but the CPU will be kept on until all partial wake locks have been released.

To turn off the screen you'll have to change the Window LayoutParams like this :

WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);
Community
  • 1
  • 1
Ashish Ranjan
  • 5,523
  • 2
  • 18
  • 39
0

I think you forgot to add this :

 wl.release();
Lubomir Babev
  • 1,892
  • 1
  • 12
  • 14
  • 1
    Added this line to be executed in `onPause()`. Did not help (as I expected). – c0dehunter Jul 15 '16 at 13:27
  • 2
    this is to release wake lock, not to turn it on and is used when you're done with the wake lock. From the docs : *This method releases your claim to the CPU or screen being on. The screen may turn off shortly after you release the wake lock, or it may not if there are other wake locks still held.* https://developer.android.com/reference/android/os/PowerManager.WakeLock.html#release() – Ashish Ranjan Jul 15 '16 at 13:28
  • But I'm trying to turn off the screen with `acquire()` (and keep CPU on). – c0dehunter Jul 15 '16 at 13:33