Android的不断广播接收器在后台 [英] Android keep BroadcastReceiver in background

查看:125
本文介绍了Android的不断广播接收器在后台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个BroadcastReceiver,它只有在最近用过菜单上显示我的应用程序运行。如果我从最近的应用程序中删除我的应用程序的广播接收器将停止工作。
我如何才能让广播接收器在后台?

我登记从我的主要活动的广播接收器(在OnCreate中())。

 的IntentFilter的IntentFilter =新的IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(接收器,IntentFilter的);广播接收器接收器=新的广播接收器(){
    @覆盖
    公共无效的onReceive(上下文的背景下,意图意图){    }
};


解决方案

这是不是你应该如何注册一个接收器。你接收器工作,因为你构建它的onCreate,这意味着只要你的应用程序还活着就会活停止。当应用程序被破坏,也失去了接收器。

如果您在活动内注册接收器,你应该总是注册它的onR​​esume和注销的onPause,这将使其可用,而活动是对用户可见。这是当你希望在用户与活动交互,有一个活跃的接收器的用例。

如果你想有一个后台接收器,你需要注册它里面的 AndroidManifest (意图过滤器)的,添加一个 IntentService ,当你在接收器接收广播启动它。

下面是一个教程,你有兴趣在第3章

如果你需要始终打开,启动一个前台服务。有一个在服务功能,您可以:<一href=\"http://developer.android.com/reference/android/app/Service.html#startForeground%28int,%20android.app.Notification%29\"相对=nofollow> 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的不断广播接收器在后台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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