Android:BroadcastReceiver在屏幕打开/关闭时通过代码了解

时间:2013-04-10 16:42:02

标签: android broadcastreceiver lifecycle

我有一个广播接收器:

public class ScreenReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {

          //Do something

        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {

            Intent start=new Intent(context,MainActivity.class);
        context.startActivity(start);
        }
    }
}

而且,在我的活动中,进入onCreate():

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

问题在于,当我的活动显示时,接收器正确执行操作,但是当它在后台时,有时没有任何反应。

可能是什么问题?

1 个答案:

答案 0 :(得分:0)

最有可能的是,当您的应用进入后台时,Android会将其杀死以释放资源。从您的Activity中尝试starting a foreground service attached to an ongoing notification,并在其中注册BroadcastReceiver。