turn the screen on/off in Android with a shake

2019-05-20 00:22发布

问题:

I'm making an app that needs to toggle the screen on/off when the user shakes the phone. So far, I've got a SensorEventListener that listens to the shakes as suggested in the answer to this question.

When I detect a shake, I change the value of the screen's brightness as suggested in this question's answer. It all works great if I don't actually turn the screen off... if I set the brightness to 0.01f through the public void setBright(float value) method it works perfectly. However, if I set the brightness to 0.0f, the phone won't turn the screen again... not until I press the power button, at least.

Is what I'm trying to do possible? what am I doing wrong?

-- EDIT --

Thanks to Dre and icyerasor I've looked further into the issue. I acquire a PARTIAL_WAKE_LOCK before I set the brightness to 0.0f, but it still doesn't turn on when I shake the phone. However, when I debug the app I see that the setBright(1.0f) gets called allright when I shake the phone with the screen turned off; My suspicion is that the lockscreen is somehow messing with it, since it kicks in when I press the power button. After I press the power button, the app continues to work as it usually does. Is there a way to bypass the lockscreen?

Thanks for your help!

回答1:

I agree with icyerasor's guess, however -- If the guess is correct and the phone is going to sleep you will have to acquire a PARTIAL_WAKE_LOCK to keep the CPU awake before you set the brightness to 0.0

I would test this before answering but I don't have access to an Android device at this moment.



回答2:

Just a guess: Setting it to brighnes 0.0 might also put the phone in sleep mode?

When you want to turn it on again programmatically, try acquiring a ACQUIRE_CAUSES_WAKEUP Wakelock:

PowerManager pm = (PowerManager)mContext.getSystemService(
                                          Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(
                                      PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                                      | PowerManager.ACQUIRE_CAUSES_WAKEUP,
                                      TAG);
wl.acquire(1000);