Attempting to put Android device to sleep, but the PowerManager does not contain a "goToSleep(long) method

时光怂恿深爱的人放手 提交于 2019-11-30 09:23:39

问题


I am attempting to put a device to sleep and I have found references all over about using the PowerManager class's goToSleep(long) method but I do not see it in the documentation and it does not work when I attempt to using it in my code.

Android's documentation does not contain a goToSleep method that I could see.

My Code:

 private void sleepDevice() {
    try {
        PowerManager powerMgr = (PowerManager) getSystemService(Context.POWER_SERVICE);
        long time = 1000;
        powerMgr.goToSleep(time);
    } catch (Exception ex) {
        updateStatus("Error attempting to reboot device.");
        updateStatus(ex.getLocalizedMessage());
    }
}

Android Studio does not let the code compile with the message, "Cannot resolve method 'goToSleep(long).

I don't even see this method as deprecated. Also, I don't need to worry about security permissions, the call is intended to run on rooted devices or fail elegantly on non-rooted devices.


回答1:


You can use the DeviceAdministrator , but you need the user to grant you those rights.




回答2:


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

Try this way and give some feedback.



来源:https://stackoverflow.com/questions/28459287/attempting-to-put-android-device-to-sleep-but-the-powermanager-does-not-contain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!