【问题标题】:Activity Listen for broadcast receiver活动监听广播接收器
【发布时间】:2016-05-14 04:04:45
【问题描述】:

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

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

【问题讨论】:

    标签: android broadcastreceiver


    【解决方案1】:

    最好的方法是注册一个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

    享受。

    【讨论】:

      【解决方案2】:

      注册BOOT_COMPLETED动作的广播接收器与活动无关,它是一个单独的组件。所以,是的,你没有对你的活动的引用,你不应该运行任何定期任务。

      我要做的是将收集到的数据写入数据库或共享首选项,然后在您的活动实际出现在屏幕上时读取它。

      如果您使用 SQLite 数据库,您可以使用ContentObserver 来通知您的活动有关基础数据的更改。这适用于装载机。

      如果是共享偏好,您可以使用在您的活动中注册的OnSharedPreferenceChangeListener

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-20
        相关资源
        最近更新 更多