[英]Activity Listen for broadcast receiver
So I have broadcast receiver that is getting started on boot.所以我有启动时开始的广播接收器。 I have an activity that using the information being collected by the broadcast receiver.
我有一个使用广播接收器收集的信息的活动。 I want the activity to be able to update its recycler view every time the broadcast receiver is called, the problem is the activity has no reference to the broadcast receiver.
我希望活动能够在每次调用广播接收器时更新其回收器视图,问题是该活动没有对广播接收器的引用。 Is there a way that I can have my activity listen for the broadcasts and update itself?
有没有办法让我的活动监听广播并自行更新?
The only thing I can think of is having the activity run a repeating task that will try to update itself with new information.我唯一能想到的是让活动运行一个重复的任务,它会尝试用新信息更新自己。 This doesn't seem like a good solution to me.
这对我来说似乎不是一个好的解决方案。
the best approach is to register a BroadcastReceiver
- see documentation on this .最好的方法是注册一个
BroadcastReceiver
- 请参阅有关此的文档。 In your case you'd want to Programmatically register a broadcast receiver so that the onReceive(Context context, Intent intent)
from inside the Activity
class.在您的情况下,您希望以编程方式注册一个广播接收器,以便
Activity
类内部的onReceive(Context context, Intent intent)
。 In this way, you can then update the Recyclerview
as you desire.这样,您就可以根据需要更新
Recyclerview
。 Something like:就像是:
public void onCreate(Bundle savedInstanceState){
...
IntentFilter filter = new IntentFilter();
//you may want to set whatever filters here...
//define the broadcast receiver
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//here you can update the RecyclerView as you desire using intent's data
}
};
//register the broadcast receiver
registerReceiver(receiver, filter);
}
I strongly recommend that you go through this nice BroadcastReceiver tutorial .我强烈建议您阅读这个不错的BroadcastReceiver 教程。
Enjoy.享受。
The broadcast receiver registered for BOOT_COMPLETED
action has nothing to do with the activity, it's a separate component.为
BOOT_COMPLETED
操作注册的广播接收器与活动无关,它是一个单独的组件。 So, yes, you don't have a reference to your activity and you should not run any periodical task.所以,是的,您没有对您的活动的引用,您不应该运行任何定期任务。
What I would do is to write the collected data to the database or shared preferences and then read it when your activity is actually on the screen.我要做的是将收集到的数据写入数据库或共享首选项,然后在您的活动实际出现在屏幕上时读取它。
If you use an SQLite database you can use a ContentObserver
to notify your activity about changes to the underlying data.如果您使用 SQLite 数据库,您可以使用
ContentObserver
来通知您的活动有关基础数据的更改。 This works great with loaders.这适用于装载机。
In case of shared preferences you can use a OnSharedPreferenceChangeListener
registered in your activity.在共享首选项的情况下,您可以使用在您的活动中注册的
OnSharedPreferenceChangeListener
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.