Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check in application if the device has been awoken or went to sleep

Tags:

android

In my android app I want to receive the notification when the device wakes up and when the device goes to sleep. Based on this I have to perform some operations. Please help.

Please note

SCREEN_ON / OFF is different. Screen might be OFF but device might still be in wake state as in case of receiving a phone call. When we place the phone against our ear prximity sensor turns off the screen, but the device does not go to sleep.

like image 314
Ankit Avatar asked Aug 06 '14 05:08

Ankit


1 Answers

There is inbuilt IntentFilters that you can capture.

Intent.ACTION_SCREEN_ON
Intent.ACTION_SCREEN_OFF

Using service and broadcastreceiver combination you can achieve that you looking for.

You will find complete demo HERE

UPDATE:

You can use some methods of PowerManager class.

PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);

if(pm.isScreenOn()){
   // not sleep
}else{
  // sleep
}

API level >=20

if(pm.isInteractive()){
   // not sleep
}else{
  // sleep
}

Explanation :

public boolean isScreenOn ()

Added in API level 7 This method was deprecated in API level 20. Use isInteractive() instead.

Returns true if the device is in an interactive state.

For historical reasons, the name of this method refers to the power state of the screen but it actually describes the overall interactive state of the device. This method has been replaced by isInteractive().

The value returned by this method only indicates whether the device is in an interactive state which may have nothing to do with the screen being on or off. To determine the actual state of the screen, use getState().

Returns True if the device is in an interactive state.

Reference HERE

like image 178
Biraj Zalavadia Avatar answered Nov 02 '22 19:11

Biraj Zalavadia