Reputation: 1215
I want to write a simple program that have only one button in main activity and the device will sleep when click on this button (like the phone sleep when we click power button on android powered smartphone). Please, help me.
Upvotes: 1
Views: 802
Reputation: 239
to make the method mentioned by pathfinderelite, will have to make the app as a system app by signing it. another work around is that , you can enable the ,
LOCAL_PRIVILEGED_MODULE := true
in your Android.mk file. this will give you the app a privileged mode. (ofcourse, you can do only if you have the firmware build workspace.. )
Upvotes: 1
Reputation: 3137
There are no public APIs that allow you to do this, prior to Lollipop. In Lollipop, you would need to be a device administrator and use DevicePolicyManager#lockNow()
as CommonsWare suggested. However, there is a trick you can use (mwahaha) to sort of accomplish what you want. First, you need the WRITE_SETTINGS permission
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
This will allow you to change certain system settings. The one we want is Settings.System.SCREEN_OFF_TIMEOUT
. You can then set the screen-timeout to 0 milliseconds, which will, after a second or two, cause the screen to turn off. After the screen turns off, you'll want to reset the timeout so that the screen doesn't constantly timeout when you don't want it to.
final int previous = Settings.System.getInt(getContentResolver(),
Settings.System.SCREEN_OFF_TIMEOUT); // retain previous timeout value
Settings.System.putInt(getContentResolver(),
Settings.System.SCREEN_OFF_TIMEOUT, 0); // set timeout to 0
// wait 3 seconds then reset the timeout setting
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Settings.System.putInt(
getContentResolver(),
Settings.System.SCREEN_OFF_TIMEOUT, previous);
}
}).start();
Warning: This is by all means a nasty hack. As such, it is not reliable. There can be a number of things that may cause this not to work. For example, an application may be explicitly keeping the device awake. There may be other system or developer settings that also keep the device from timing-out - when the device is plugged-in, for example. The bottom line is, Android doesn't want your app to have the ability to do this, and you should probably learn to accept it.
Upvotes: 1