Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can I notify a running activity from a broadcast receiver?

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?

like image 914
Henry Avatar asked Jun 26 '10 03:06

Henry


People also ask

How a notification manager and broadcast receiver works under Android?

Broadcast in android is the system-wide events that can occur when the device starts, when a message is received on the device or when incoming calls are received, or when a device goes to airplane mode, etc. Broadcast Receivers are used to respond to these system-wide events.

What method is used to send a broadcast event?

Sending broadcasts The sendOrderedBroadcast(Intent, String) method sends broadcasts to one receiver at a time.

How notification and broadcast is used in Android Studio?

A broadcast receiver is a dormant component of the Android system. Only an Intent (for which it is registered) can bring it into action. The Broadcast Receiver's job is to pass a notification to the user, in case a specific event occurs. Using a Broadcast Receiver, applications can register for a particular event.


1 Answers

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.

like image 96
Rich Schuler Avatar answered Oct 13 '22 18:10

Rich Schuler