8

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.

user256239
  • 17,717
  • 26
  • 77
  • 89

2 Answers2

4

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);
Moritz
  • 10,124
  • 7
  • 51
  • 61
  • 4
    Or, just don't use a `WAKEUP` alarm and stick with `setRepeating()`. If you tell the alarm not to wake up the phone, it won't. – CommonsWare Mar 01 '10 at 23:09
2

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>
Nik
  • 7,114
  • 8
  • 51
  • 75
  • 2
    This doesn't work: unfortunately, you can't register SCREEN_ON or SCREEN_OFF in the AndroidManifest.xml; you need to do it in code (not sure why that is, but I've tested and confirmed that). – Shawn Lauzon Apr 25 '12 at 18:34
  • 1
    See http://stackoverflow.com/a/1588267/338479 for the reasoning. Unfortunately, you need to look at the source code to see which broadcasts require your receiver be registered via registerReceiver(BroadcastReceiver, IntentFilter) instead of the manifest. – Edward Falk Dec 14 '12 at 02:35
  • 1
    +1 if you register `SCREEN_ON`/`SCREEN_OFF` in a sticky service, you can be quite sure that they will stay active even if the device is going to sleep mode. In particlular if you start this service in forground ... :) – Trinimon Aug 21 '13 at 07:19