When i have a broadcastReceiver say android.intent.action.MEDIA_BUTTON and i want to update the current activity's UI without creating a new activity, is there any good practice on this one?
What i know (might not be correct)
1) I can put the BroadcastReceiver in the same class as the activity and call the updateUI function after certain activity
2) Create a ContentObserver?
3) Communicate to a service created by the activity, use aidl. (I dont know how to get the current service if its registered from an activity)
4) Create a custom filter on the broadcastReceiver located on the same class as the activity, and use context.sendBroadcast(msg of custom filter) and in the custom filter call updateUI (same as one but more generic?)
The final flow is it would come from a BroadcastReceiver and ends up updating the UI without renewing the activity (unless the activity is dead?)
Kindly provide links/source code on your how you tackle this kind of problem. Thanks a lot in advance :)
Step 1. Open your project where you want to implement this. Step 2. Open your BroadcastReceiver class from where you pass data to activity inside your onReceive() you need to start intent and pass data inside intent and start sendBroadcast() as shown bellow.
A BroadcastReciever life cycle ends (ie stop receiving broadcast) when you unregister it. usually you would do this in the onPause/onStop method.
A Service receives intents that were sent specifically to your application, just like an Activity. A Broadcast Receiver receives intents that were broadcast system-wide to all apps installed on the device.
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.
The easiest way to provide this functionality is to put the broadcast receiver in you Activity and bind / unbind it using registerReceiver and unregisterreceiver:
public class MyActivity extends Activity { private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { MyActivity.this.receivedBroadcast(intent); } }; @Override public void onResume() { super.onResume(); IntentFilter iff = new IntentFilter(); iff.addAction("android.intent.action.MEDIA_BUTTON"); // Put whatever message you want to receive as the action this.registerReceiver(this.mBroadcastReceiver,iff); } @Override public void onPause() { super.onPause(); this.unregisterReceiver(this.mBroadcastReceiver); } private void receivedBroadcast(Intent i) { // Put your receive handling code here } }
Depending on the intent you wish to receive, you may need to add the appropriate permissions to your AndroidManifest.xml file.
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