SCREEN_OFF BroadcastReceiver 不工作

SCREEN_OFF BroadcastReceiver is not working

这是我的代码。

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 被检测到并正常工作

但是,Intent.ACTION_SCREEN_OFF(android.intent.action.SCREEN_OFF)在屏幕关闭时未检测到。

这个Activity是从Service开始的(从其他接收者开始)。

我有什么问题吗?

unregister 移至 onDestroy。屏幕关闭时,onStop正在通话。

参考https://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle

如果 activity 不再可见,将调用 onStop 方法。

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

    unregisterReceiver(broadcastReceiver);
}