Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

android

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.

like image 661
user256239 Avatar asked Mar 01 '10 23:03

user256239


2 Answers

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);
like image 64
Moritz Avatar answered Nov 15 '22 10:11

Moritz


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>
like image 37
Nik Avatar answered Nov 15 '22 12:11

Nik