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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With