another application) so that you can inform it of something happening.
Intents are capable of sending structured messages across process boundaries.
Intents can be used to broadcast messages anonymously between components via the sendBroadcast method
Implement Broadcast Receivers to listen for, and respond to, these broadcast Intents within your
applications
Broadcasting an event using an Intent lets you and third-party developers react to events without having to modify your original application.
Android uses broadcast Intents extensively to broadcast system events like battery-charging levels,
network connections, and incoming calls.
https://github.com/coderetriever/Android/tree/master/UsingBroadcastReceiver
https://github.com/coderetriever/Android/tree/master/UpdateActivityFromABroadcastReceiver
https://github.com/coderetriever/Android/tree/master/InvokingActivityFromABroadcastReceiver
Summary
Broadcasting events with Intents
- construct the Intent you want to broadcast and use the sendBroadcast method to send it
- Set the action, data, and category of your Intent in a way that lets Broadcast Receivers accurately determine their interest
public static final String NEW_LIFEFORM_DETECTED = "com.paad.action.NEW_LIFEFORM";
Intent intent = new Intent(NEW_LIFEFORM_DETECTED);
intent.putExtra("lifeformName", lifeformType);
intent.putExtra("longitude", currentLongitude);
intent.putExtra("latitude", currentLatitude);
sendBroadcast(intent);
Listening for Broadcasts with Broadcast Receivers
- used to listen for broadcast Intents
- Broadcast Receiver to be enabled it needs to be registered, either in code or within the application manifest
Registering Broadcast Receivers in Your Application Manifest
- add a <receiver> tag within the application node, specifying the class name of the Broadcast Receiver to register
- The receiver node needs to include an intent-filter tag that specifies the action string being listened for
- Broadcast Receivers registered this way are always active, and will receive broadcast Intents even when the application has been killed or hasn’t been started
<receiver android:name=".LifeformDetectedBroadcastReceiver">
<intent-filter>
<action android:name="com.paad.action.NEW_LIFEFORM"/>
</intent-filter>
</receiver>
Registering a Broadcast Receiver in code
- Receiver registered programmatically will respond to broadcast Intents only when the application component it is registered within is running
// Create and register the broadcast receiver.
IntentFilter filter = new IntentFilter(NEW_LIFEFORM_DETECTED);
LifeformDetectedBroadcastReceiver r = new LifeformDetectedBroadcastReceiver();
registerReceiver(r, filter);
To un-register a Broadcast Receiver
unregisterReceiver(receiver);
Implementing Broadcast Receiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//TODO: React to the Intent received.
}
}
import android.content.Context;
import android.content.Intent;
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//TODO: React to the Intent received.
}
}
onReceive method will be executed when a broadcast Intent is received that matches the Intent Filter used to register the Receiver.
The onReceive handler must complete within five seconds or the Force Close dialog will be displayed
Typically Broadcast Receivers will update content, launch Services, update Activity UI, or notify the
user using the Notification Manager
Assigning Priorities to Broadcast Receivers
When you send a broadcast using the sendBroadcast() method, all the broadcast receivers that
match the specified action are called in random fashion
To programmatically assign a priority to a broadcast receiver, use the setPriority() method:
The setPriority() method takes a priority value between 0 (default) and 1,000. The larger the
number, the higher priority it has. If more than one broadcast receiver has the same priority, they are
called randomly.
To set the priority of broadcast receivers in the AndroidManifest.xml file, use the android:priority attribute
<receiver android:name=".MySecondBroadcastReceiver" >
<intent-filter android:priority="50">
<action android:name="MY_SPECIFIC_ACTION" />
</intent-filter>
</receiver>
sendOrderedBroadcast
To send a broadcast that is delivered to broadcast receivers with higher priority first, use the sendOrderedBroadcast() method, passing it an Intent object, plus any additional permission that the receiver must have in order to receive your broadcast
If you want to send a broadcast to only broadcast receivers with the permission to access the
Internet, you will specify the permission in the second argument of the sendOrderedBroadcast()
method, like this
sendOrderedBroadcast(i, “android.permission.INTERNET”);
Aborting a broadcast
When a broadcast receiver of higher priority receives the broadcast, it will handle that and the broadcast will be passed to the next broadcast receiver in line.
If you want to handle the broadcast and stop the broadcast from being propagated to the next receiver. To do that, you can use the abortBroadcast() method in onReceive method
NOTE:
In order to call the abortBroadcast() method to abort a broadcast, you need to send the broadcast using the sendOrderedBroadcast() method. Using the sendBroadcast() method has no effect on the priority and will not cause a broadcast to be aborted.
Example
Establishing communication between a service and an activity
public class MyIntentService extends IntentService
{
public MyIntentService(String name) {
super("MyIntentServiceName");
// TODO Auto-generated constructor stub
}
protected void onHandleIntent(Intent intent)
{
try
{
int result = downloadFile(new URL("http://www.amazon.com/somefile.pdf"));
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("FILE_DOWNLOADED_ACTION");
getBaseContext().sendBroadcast(broadcastIntent);
}catch(MalformedURLException e)
{
e.printStackTrace();
}
}
}
public class ServiceActivity extends Activity {
IntentFilter intentFilter;
private BroadcastReceiver intentReceiver = new BroadcastReceiver()
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(getBaseContext(), "File downloaded!", Toast.LENGTH_LONG).show();
}
};
@Override
public void onResume()
{
super.onResume();
intentFilter = new IntentFilter();
intentFilter.addAction("FILE_DOWNLOAD_ACTION");
//registering a broadcast receiver through code
registerReceiver(intentReceiver, intentFilter);
}
@Override
public void onPause()
{
unregisterReceiver(intentReceiver);
}
}
Broadcasting Ordered Intents
- In circumstances where the order in which the Broadcast Receivers receive the Intent is important,
- or where you require the Receivers to be able to affect the Intent being broadcast, use sendOrderedBroadcast method.
- Intent will be delivered to all registered Receivers in order of priority
sendOrderedBroadcast(intent, null);
Can optionally assign your own Broadcast Receiver, which will then receive the Intent after it has been
handled (and potentially modified) by all the other registered Broadcast Receivers
sendOrderedBroadcast(intent, null, myBroadcastReceiver, null, Activity.RESULT_OK, null, null);
Broadcasting Sticky Intents

No comments:
Post a Comment