How Do I Detect When Android Device Screen Is About To Timeout Or "lock"?
Solution 1:
You will need to register a broadcast reciever.Your system will send a brodcast when device is going to sleep. Put the following code wherever desired:
privateBroadcastReceiverreceiver=newBroadcastReceiver() {
publicvoidonReceive(final Context context, final Intent intent) {
//check if the broadcast is our desired oneif (intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
//here define your method to be executed when screen is going to sleep
}};
you will need to register your receiver:
IntentFilterregFilter=newIntentFilter();
// get device sleep evernt
regFilter .addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(receiver, regFilter );
ACTION_SCREEN_OFF is sent after the screen turns off and ACTION_SCREEN_ON is sent after the screen turns on.
UPDATE:
1.Method 1: As far as i know, you can not setup a listener before ur device goes to sleep.There is no such listener inside PowerManager. A solution which comes to my mind is to get the device time out from the settings and then setup a count down timer in your app. The countdown should be reset every time user touches screen. This way you may guess the time when the device goes to sleep and then setup a wakelock before the device goes to sleep and run your desired code and after that,disable the wakelock and the put the device to sleep.
2.Method 2: inPause() method of your activity is called when your device goes to sleep. You might be able to do some code there.Just a thought.
Solution 2:
You have to use "Wakelock".. try this code
PowerManagerpm= (PowerManager)getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "whatever");wl.acquire();
And don't forget to take permission in your menifest "android.permission.WAKE_LOCK" and write wl.release() in your pouse() method..
Post a Comment for "How Do I Detect When Android Device Screen Is About To Timeout Or "lock"?"