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

2

6

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.

Montague answered 11/2, 2015 at 16:23 Comment(4)
My question is, is there another method/technique that I can use to put an Android device to sleep? Is this method is another class? Where did the goToSleep method go?Montague
goToSleep() was removed from PowerManager in API level 21 (Lollipop), why I don't know. developer.android.com/sdk/api_diff/preview-21/changes/…Overcapitalize
old Android docs (thanks to Web Archive) also state you would have needed DEVICE_POWER permission which isn't available to 3rd party apps on unrooted devices.Overcapitalize
Thanks @PhilippReichart, that was very confusing. Seeing references in the message boards but no where in the documentation or API.Montague
M
0

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

Mushroom answered 11/2, 2015 at 16:28 Comment(3)
The device administration APIs only let you lock the device, AFAIK. Whether that qualifies as "put it to sleep" for the OP's needs or not, I do not know.Pick
@Pick - yes you are right :D, it all depends on the needs of the OPMushroom
@DanieIM. Thanks for the help. I actually just need the screen to power off but I do not want to lock the device. It was decided that we can ignore this requirement for now. The closest I got to getting this to work was to set the sleep timer to zero and let the device shut the screen off. Then, I resent the timer when the user restarts the device.Montague
I
-3
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.

Immobilize answered 11/2, 2015 at 16:40 Comment(2)
This answer is not relevant to the issueGayle
This is wrong approach, question is about going to sleep.Ribble

© 2022 - 2024 — McMap. All rights reserved.