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