Android 将 BroadcastReceiver 保持在后台 [英] Android keep BroadcastReceiver in background

查看:38
本文介绍了Android 将 BroadcastReceiver 保持在后台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 BroadcastReceiver,它仅在我的应用显示在最近的应用菜单中时运行.如果我从最近的应用程序中删除我的应用程序,BroadcastReceiver 将停止工作.如何将 BroadcastReceiver 保持在后台?

我从我的主要活动(在 OnCreate() 中)注册了 BroadcastReceiver.

IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);注册接收器(接收器,意图过滤器);广播接收器接收器 = 新广播接收器(){@覆盖public void onReceive(上下文上下文,意图意图){}};

解决方案

这不是您应该注册接收器的方式.您的接收器停止工作,因为您在 onCreate 中构造它,这意味着只要您的应用程序还活着,它就会一直存在.当应用程序被破坏时,你也会失去接收器.

如果您在活动中注册接收器,则应始终在 onResume 中注册它并取消注册 onPause,这将使其在活动对用户可见时可用.这是一个用例,当您希望在用户与 Activity 交互时有一个活动的接收器.

如果你想要一个后台接收器,你需要在 AndroidManifest 中注册它(带意图过滤器),添加一个 IntentService 并在你收到广播时启动它接收方.

这是一个教程,你对第3章感兴趣.>

如果您需要始终在线,请启动前台服务.服务中有一个功能可以让你:startForeground.然后在创建服务时注册您的接收器,并在其销毁时取消注册.不过前台服务很讨厌.

I created a BroadcastReceiver and it runs only when my app shown in recent apps menu. If I remove my app from the recent apps the BroadcastReceiver will stop working. How can I keep the BroadcastReceiver in background?

I register the BroadcastReceiver from my main activity (in OnCreate()).

IntentFilter intentFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(receiver, intentFilter);

BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

    }   
};

解决方案

This is not how you should register a receiver. You receiver stops working, because you construct it in onCreate, which means it will live as long as your app is alive. When the app gets destroyed, you also lose the the receiver.

If you register receiver inside an activity, you should always register it in onResume and deregister onPause, which will make it available while the activity is visible to the user. This is a use case when you want to have an active receiver while user interacts with an activity.

If you want a background receiver, you need to register it inside the AndroidManifest (with intent filter), add an IntentService and start it when you receive a broadcast in the receiver.

Here is a tutorial, you are interested in chapter 3.

If you need to be always on, start a foreground service. There is function in Service that lets you: startForeground. Then register your receiver when service is created and deregister when it's destroyed. Foreground services are quite nasty though.

这篇关于Android 将 BroadcastReceiver 保持在后台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆