开发者

How to detect whether the phone is in sleep mode in the code?

开发者 https://www.devze.com 2022-12-21 11:19 出处:网络
Is there any way to detect whether an android phone is in sleep mode (screen is black) in the code? I wrote a home screen widget. I don\'t want the widget gets updated开发者_开发问答 when the screen i

Is there any way to detect whether an android phone is in sleep mode (screen is black) in the code? I wrote a home screen widget. I don't want the widget gets updated开发者_开发问答 when the screen is black to save the battery consumption.

Thanks.


You could use the AlarmManager to trigger the refreshes of your widget. When scheduling your next cycle you can define whether to wake up your device (aka perform the actual task).

alarmManager.set(wakeUpType, triggerAtTime, pendingIntent);


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

Little 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>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号