即使在onDestroy()之后也可以监听屏幕电源开/关

时间:2016-03-31 20:14:10

标签: android broadcastreceiver

我正在尝试在我的应用程序中监听屏幕开机/关机但是在onDestroy()之后,因为应用程序被销毁,它的停止监听是否有任何方式让我的应用程序在关闭后像后台进程一样继续收听?

BroadcastReceiver类:

public class ScreenReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent i) {
                if (i.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                        System.out.println("Screen turned off");
                } else if(i.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                        System.out.println("Screen turned on");
                }
        }
}

我将此代码放在我的主要活动

中的onCreate()中
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);

1 个答案:

答案 0 :(得分:0)

如果您在ScreenReceiver注册了AndroidManifest,即使您的应用已被销毁,您也会收到广播。只有当用户强制通过设置

停止应用时,您才能获得广播

类似

<receiver android:name=".ScreenReceiver">
    <intent-filter>
        <action android:name="action_looking_for"/>
    </intent-filter>
</receiver>