androidbroadcastreceiverscreen-off

SCREEN_OFF BroadcastReceiver is not working


This is my code.

public class MyActivity extends Activity {
    ...
    @Override
    protected void onStart() {
        super.onStart();

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.my.ACTION");
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);

        registerReceiver(broadcastReceiver, intentFilter);
    }

    @Override
    protected void onStop() {
        super.onStop();

        unregisterReceiver(broadcastReceiver);
    }

    ...

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if ("com.my.ACTIOIN".equals(action)) {
                updateMessageInformation(intent);
                updateDialog();
            } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                finish();
            }
        }
    };
    ...
}

com.my.ACTION is detected and working correctly

But, Intent.ACTION_SCREEN_OFF(android.intent.action.SCREEN_OFF) is not detected when the screen turn off.

This Activity is start from Service(start from other receiver).

What would I have anything wrong?


Solution

  • Move the unregister to onDestroy. When screen turn off, onStop is calling.

    Reference to https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

    If the activity is no longer visible, onStop method is called.

    @Override
    protected void onDestroy() {
        super.onDestroy();
    
        unregisterReceiver(broadcastReceiver);
    }