I have little concern about register BroadcastReceiver: Because Android support quite flexible, it allow BroadcastReceiver register by 2 method: In Manifest.xml setting and Via implement source code:
Example:
❶ Via Manifest.xml
<intent-filter>
<action android:name="YourBroadcastMesssage" />
</intent-filter>
❷ Register thought implement of source code:
IntentFilter filter = IntentFilter("BroadcastMessage");
filter.addAction("BroadcastMessage");
context.registerReceiver(BroadcastListener, filter);
enter code here
★I think one of difference is unregister able:
★Question:
I still don't known exactly when to use ❶ or ❷ and which is better?
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.
Receiver can be registered via the Android manifest file. You can also register and unregister a receiver at runtime via the Context. registerReceiver() and Context. unregisterReceiver() methods.
Creating a BroadcastReceiver The 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.
IMO, you must register the BroadcastReceiver from code when you want to execute things in that activity directly once the broadcast has been caught (e.g. finish the activity).
When you want to perform other kind of tasks which don't require the activity, use the XML setting (e.g. launching a Toast to show some info).
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