Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegisterBroadcastReceiver in Manifest.xml setting or by implement source code

Tags:

android

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:

  1. Implement ❶ mean always handler registed broadcast message.
  2. Implement ❷ for in case don't want to handler Broadcast message, can unregister that broadcast message

Question:

I still don't known exactly when to use ❶ or ❷ and which is better?

like image 375
NguyenDat Avatar asked Feb 25 '11 00:02

NguyenDat


People also ask

What are broadcast receivers How is it implemented?

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.

Where do I register and unregister broadcast receiver?

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.

What is the role of the onReceive () method in the BroadcastReceiver?

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.


1 Answers

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).

like image 169
Cristian Avatar answered Oct 18 '22 20:10

Cristian