How to determine if the phone is in sleep mode in code?

Is there a way to determine if the Android phone is in sleep mode (black screen) in the code? I wrote a home screen widget. I do not want the widget to update when the screen is black to save battery consumption.

Thanks.

+4
source share
2 answers

You can use AlarmManager to start updating your widget. When you plan your next cycle, you can determine if you need to wake up your device (otherwise do the actual task).

alarmManager.set(wakeUpType, triggerAtTime, pendingIntent); 
+3
source

You can use a broadcast receiver with android.intent.action.SCREEN_ON and android.intent.action.SCREEN_OFF action filters

A small example:

Your receiver:

  public class ScreenOnOffReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { // some code } if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { // some code } } } 

Your manifest:

  <receiver android:name=".ScreenOnOffReceiver"> <intent-filter> <action android:name="android.intent.action.SCREEN_ON" /> <action android:name="android.intent.action.SCREEN_OFF" /> </intent-filter> </receiver> 
+1
source

Source: https://habr.com/ru/post/1302810/


All Articles