简体   繁体   中英

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 . 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. In this way, you can then update the Recyclerview as you desire. 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 .

Enjoy.

The broadcast receiver registered for BOOT_COMPLETED action has nothing to do with the activity, it's a separate component. 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. This works great with loaders.

In case of shared preferences you can use a OnSharedPreferenceChangeListener registered in your activity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM