28

I have an activity, it needs to response to a broadcast event. Since an activity can not be a broadcast receiver at the same time, I made a broadcast receiver.

My question is: how can I notify the activity from the broadcast receiver? I believe this is a common situation, so is there a design pattern for this?

Brais Gabin
  • 5,827
  • 6
  • 57
  • 92
Henry
  • 942
  • 3
  • 11
  • 21

1 Answers1

41

The broadcast is the notification. :) If you want to say, start an activity or a service, etc., based on a received broadcast then you need a standalone broadcast receiver and you put that in your manifest file. However, if you want your activity itself to respond to broadcasts then you create an instance of a broadcast receiver in your activity and register it there.

The pattern I use is:

public class MyActivity extends Activity {
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(...) {
            ...
        }
   });

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

        IntentFilter filter = new IntentFilter();
        filter.addAction(BROADCAST_ACTION);

        this.registerReceiver(this.receiver, filter);
    }

    public void onPause() {
        super.onPause();

        this.unregisterReceiver(this.receiver);
    }
}

So, this way the receiver is instantiated when the class is created (could also do in onCreate). Then in the onResume/onPause I handle registering and unregistering the receiver. Then in the reciever's onReceive method I do whatever is necessary to make the activity react the way I want to when it receives the broadcast.

Community
  • 1
  • 1
Rich Schuler
  • 41,814
  • 6
  • 72
  • 59
  • 11
    So you have to define the receiver inside the activity? What if you want the behaviour throughout your app? – shim Nov 11 '12 at 01:30
  • Further clarification: `String BROADCAST_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";` Also, I you want a behavior throughout your app, couldn't you take take code in the class extending `Application`? – Sunshinator Nov 15 '16 at 16:13
  • So the broadcast is lost if the activity is not STARTED? This may not be desirable. – kodu Jan 22 '19 at 09:48