How to turn screen off or send device to sleep

2019-02-08 15:54发布

问题:

I want to send device to sleep or turn the screen off. I have investigated and found this topic: Turn off screen on Android

Basically, the are three ways to do it, but I have found problems for the three:

a) Choice 1:

PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE);
manager.goToSleep(int amountOfTime);

Problem: It causes FC. I have read I need DEVICE_POWER permissions, but it can't be granted for normal apps.

b) Choice 2:

PowerManager manager = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = manager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Your Tag");
wl.acquire();
wl.release();

Problem: This does not work for me. I don't know why. It does not give me a FC, but it is innocuous.

c) Choice 3:

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

Problem: I can get it to work but when try to turn on device it does strange things, like don't like to return, or if my apps is in front, automatically goes to sleep just after pressing on button. This looks more like a tip or workaround than normal solution.

Can anyone tell me any good method to send device to sleep or turn screen off that can run without problems? It sound rare to me that a simple functionality like this has not a good way to use it (or at lest well documented)

回答1:

I answer myself. It is possible to turn off the device, but the application has to implement the device administrator feature via API: Device Administration

In this API there is a locknow() function that do what I want.

Anyway, this is for extending the android hardware and security features and it is very unlikely that anyone wants to control the device in that way.

What I wanted is the ability to lock the device from a simple gesture. As I dont want to make my own device manager class I check if the free application "lockScreen" is installed and launch it. It is a shortcut and an easy way to do what I want. This app must be register as device manager so it has implemented this class. It is possible to get it free from the market.



回答2:

My application already does this fine, I found this in my PowerManager.class

 /**
 * Force the device to go to sleep. Overrides all the wake locks that are
 * held.
 * 
 * @param time is used to order this correctly with the wake lock calls. 
 *          The time  should be in the {@link SystemClock#uptimeMillis 
 *          SystemClock.uptimeMillis()} time base.
 */
public void goToSleep(long time) 
{
    try {
        mService.goToSleep(time);
    } catch (RemoteException e) {
    }
}