Home » Android » android – BroadcastReceiver lifecycle

android – BroadcastReceiver lifecycle

Posted by: admin May 14, 2020 Leave a comment

Questions:

1) I have an Activity. This Activity starts a service, which in turn creates and registers a BroadcastReceiver.

2) I have an Activity. This Activity creates and registers a BroadcastReceiver.

When does BroadcastReceiver’s life end in each of the above cases? In other words – when it gets destroyed and won’t listen to broadcasts anymore?

How to&Answers:

Declare broadcast receiver in manifest to achieve independent life cycle for it.

http://developer.android.com/reference/android/content/BroadcastReceiver.html

Answer:

Only onReceive() method is called in BroadcastReciver’s life cycle.

Answer:

A BroadcastReciever life cycle ends (ie stop receiving broadcast) when you unregister it. usually you would do this in the onPause/onStop method. but it’s up to you technically.

Example:

@Override
public void onResume() {
  super.onResume();

  // Register mMessageReceiver to receive messages.
  LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
      new IntentFilter("my-event"));
}

// handler for received Intents for the "my-event" event 
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
  @Override
  public void onReceive(Context context, Intent intent) {
    // Extract data included in the Intent
    String message = intent.getStringExtra("message");
    Log.d("receiver", "Got message: " + message);
  }
};

@Override
protected void onPause() {
  // Unregister since the activity is not visible
  LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
  super.onPause();
}