Home » Android » How to register to sleep event in Android?

How to register to sleep event in Android?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am working on Android 3.0 and I need to know in my application when the device goes on sleep / turn off screen.

How can I register to this intent/event so I will be able to run some actions when this happens? Is there any action in BroadcastReceiver that notifies for this?

How to&Answers:

This page has a tutorial on exactly what you’re looking for.

Code copied from that page (in order to turn this from a link-only answer to something directly useful):

1) Create a class in your application to receive the intent. For example, the following receiver stands alone and sets a static variable to be used in part 2:

public class ScreenReceiver extends BroadcastReceiver {
    public static boolean wasScreenOn = true;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            // do whatever you need to do here
            wasScreenOn = false;
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            // and do whatever you need to do here
            wasScreenOn = true;
        }
    }
}

2) Modify your activity to receive screen on/off events. Your receiver will check the static variable in your broadcast receiver to know the reason for the intent you just received:

public class ExampleActivity extends Activity {
   @Override
    protected void onCreate() {
        // initialize receiver
        IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        BroadcastReceiver mReceiver = new ScreenReceiver();
        registerReceiver(mReceiver, filter);
        // your code
    }

    @Override
    protected void onPause() {
        // when the screen is about to turn off
        if (ScreenReceiver.wasScreenOn) {
            // this is the case when onPause() is called by the system due to a screen state change
            System.out.println("SCREEN TURNED OFF");
        } else {
            // this is when onPause() is called when the screen state has not changed
        }
        super.onPause();
    }

    @Override
    protected void onResume() {
        // only when screen turns on
        if (!ScreenReceiver.wasScreenOn) {
            // this is when onResume() is called due to a screen state change
            System.out.println("SCREEN TURNED ON");
        } else {
            // this is when onResume() is called when the screen state has not changed
        }
        super.onResume();
    }
}