开发者

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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜