gpt4 book ai didi

android - 监听广播接收器的 Activity

转载 作者:搜寻专家 更新时间:2023-11-01 09:47:38 25 4
gpt4 key购买 nike

所以我有在启动时开始的广播接收器。我有一个使用广播接收器收集的信息的 Activity 。我希望 Activity 能够在每次调用广播接收器时更新其回收器 View ,问题是该 Activity 没有引用广播接收器。有没有办法让我的 Activity 收听广播并自行更新?

我唯一能想到的就是让 Activity 运行一个重复任务,尝试用新信息更新自身。这对我来说似乎不是一个好的解决方案。

最佳答案

最好的方法是注册一个BroadcastReceiver - 参见documentation on this .在您的情况下,您想要 Programmatically register a broadcast receiver这样 onReceive(Context context, Intent intent) 来自 Activity 类。这样,您就可以根据需要更新 Recyclerview。像这样的东西:

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);
}

我强烈建议您阅读这个不错的 BroadcastReceiver tutorial .

享受吧。

关于android - 监听广播接收器的 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37218238/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com