1

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?

4

1 回答 1

0

移动unregisteronDestroy。当屏幕关闭时,onStop正在通话。

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

如果活动不再可见,onStop则调用方法。

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

    unregisterReceiver(broadcastReceiver);
}
于 2016-03-21T07:51:08.810 回答