Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start BroadCastReceiver From Activity

Tags:

android

I want to start a BroadcastReceiver from an Activity. How can I do that?

like image 869
Sri Sri Avatar asked Jan 25 '11 14:01

Sri Sri


People also ask

How do I start a broadcast receiver?

Creating a BroadcastReceiverThe onReceiver() method is first called on the registered Broadcast Receivers when any event occurs. The intent object is passed with all the additional data. A Context object is also available and is used to start an activity or service using context. startActivity(myIntent); or context.

What is the life cycle of BroadcastReceiver?

A BroadcastReceiver object is only valid for the duration of the call to onReceive(Context, Intent) . Once your code returns from this function, the system considers the object to be finished and no longer active.

How pass data from BroadcastReceiver to activity in Android?

getStringExtra("message"); And then you will use message as you need. If you simply want the ReceiveText activity to show the message as a dialog, declare <activity android:theme="@android:style/Theme. Dialog" /> in your manifest for ReceiveText and then set the message to a textview in the activity.


1 Answers

Define your BroadcastReceiver:

private final BroadcastReceiver             receiver
    = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Do something
    }
};

Register your receiver in onResume:

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

    IntentFilter filter = new IntentFilter();
    filter.addAction("SOME_ACTION");
    registerReceiver(receiver, filter);
}

Unregister the receiver in onPause:

@Override
protected void onPause() {
    super.onPause();

    unregisterReceiver(receiver);
}
like image 178
Erich Douglass Avatar answered Sep 22 '22 13:09

Erich Douglass