Context: I'm under Android 4.0.4. The code I'm stating is inside an Activity. The application is a Cordova application, I'm writing this code inside a plugin. I think I read all the questions here in StackOverflow and the Android docs.
I want to acquire a wakelock, wake up the device, do some stuff and then, when the wakelock is released, i want the screen to turn off again and let the phone sleep. I have tried several approaches:
I tried several examples found here to wake up the device. The only way I managed to turn the device on programatically was aquiring a wakelock with the ACQUIRE_CAUSES_WAKEUP flag. This works fine. The problem comes when I release the wakelock. There's no way I can turn the screen off again. It just stays on forever. I tried with all the WAKELOCKS available and with all the FLAGS available. Note:I'm not totally happy with this approach because as stated in the docs, the only wakelock that is not deprecated is the partial wakelock, which unfortunately can't be used with this flag.
As I couldn't find any way of letting the screen off using the wakelocks functionality I tried to turn it off programmatically. I think I tried all the examples found here to turn the screen off, and the only one which worked was:
params.flags |= LayoutParams.FLAG_KEEP_SCREEN_ON;
params.screenBrightness = 0;
getWindow().setAttributes(params);
The problem is that using this method I can't turn it on again. When I acquire the wakelock again it just stays off. Also, when I try to wake up the phone pressing the "home" button it doesnt wake up. It only responds after pressing 3 or 4 times the "power" button. Seems like this approach freezes the phone.
I tried to turn on the screen programmatically before acquiring (and before too) the wakelock, restoring the default brightness value using the same code as above, but It doesn't work.
It's almost a week that I'm struggling with this. Any piece of advice will be appreciated.