I want to start a BroadcastReceiver
from an Activity
. How can I do that?
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With