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>
精彩评论