Intents to Broadcast Events in Android

Broadcast Intents are used to notify applications of system or application events, extending the event-driven programming model between applications

Broadcasting Intents helps make your application more open; by broadcasting an event using an Intent, you let yourself and third-party developers react to events without having to modify your original application. Within your applications you can listen for Broadcast Intents to to react to device state changes and third-party application events

Android uses Broadcast Intents extensively to broadcast system events, such as changes in network connectivity, docking state, and incoming calls.

Broadcasting Events with Intents

Within your application, construct the Intent you want to broadcast and call sendBroadcast to send it.

Set the action, data, and category of your Intent in a way that lets Broadcast Receivers accurately determine their interest. In this scenario, the Intent action string is used to identify the event being broadcast, so it should be a unique string that identifies the event. By convention, action strings are constructed using the same form as Java package names:

public static final String NEW_LIFEFORM_DETECTED = 
 “com.paad.action.NEW_LIFEFORM”;

If you want to include data within the Intent, you can specify a URI using the Intent’s data property. You can also include extras to add additional primitive values. Considered in terms of an event driven paradigm, the extras equate to optional parameters passed into an event handler.

Broadcasting an Intent

Intent intent = new Intent(LifeformDetectedReceiver.NEW_LIFEFORM);
intent.putExtra(LifeformDetectedReceiver.EXTRA_LIFEFORM_NAME,
 detectedLifeform);
intent.putExtra(LifeformDetectedReceiver.EXTRA_LONGITUDE,
 currentLongitude);
intent.putExtra(LifeformDetectedReceiver.EXTRA_LATITUDE,
 currentLatitude);
sendBroadcast(intent);

Listening for Broadcasts with Broadcast Receivers

Broadcast Receivers (commonly referred to simply as Receivers) are used to listen for Broadcast Intents. For a Receiver to receive broadcasts, it must be registered, either in code or within the application manifest — the latter case is referred to as a manifest Receiver. In either case, use an Intent Filter to specify which Intent actions and data your Receiver is listening for.

In the case of applications that include manifest Receivers, the applications don’t have to be running when the Intent is broadcast for those receivers to execute; they will be started automatically when a matching Intent is broadcast. This is excellent for resource management, as it lets you create event-driven applications that will still respond to broadcast events even after they’ve been closed or killed.

To create a new Broadcast Receiver, extend the BroadcastReceiver class and override the onReceive event handler:

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

The onReceive method will be executed on the main application thread when a Broadcast Intent is received that matches the Intent Filter used to register the Receiver. The onReceive handler must complete within five seconds; otherwise, 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. The five-second execution limit ensures that major processing cannot, and should not, be done within the Broadcast Receiver itself.

Implementing a Broadcast Receiver

public class LifeformDetectedReceiver 
 extends BroadcastReceiver {
 public final static String EXTRA_LIFEFORM_NAME 
 = “EXTRA_LIFEFORM_NAME”;
 public final static String EXTRA_LATITUDE = “EXTRA_LATITUDE”;
 public final static String EXTRA_LONGITUDE = “EXTRA_LONGITUDE”;
 public static final String 
 ACTION_BURN = “com.paad.alien.action.BURN_IT_WITH_FIRE”;
public static final String 
 NEW_LIFEFORM = “com.paad.alien.action.NEW_LIFEFORM”;
 @Override
 public void onReceive(Context context, Intent intent) {
 // Get the lifeform details from the intent.
 Uri data = intent.getData();
 String type = intent.getStringExtra(EXTRA_LIFEFORM_NAME);
 double lat = intent.getDoubleExtra(EXTRA_LATITUDE, 0);
 double lng = intent.getDoubleExtra(EXTRA_LONGITUDE, 0);
 Location loc = new Location(“gps”);
 loc.setLatitude(lat);
 loc.setLongitude(lng);
 if (type.equals(“facehugger”)) {
 Intent startIntent = new Intent(ACTION_BURN, data);
 startIntent.putExtra(EXTRA_LATITUDE, lat);
 startIntent.putExtra(EXTRA_LONGITUDE, lng);
 context.startService(startIntent);
 }
 }
}

Registering and unregistering a Broadcast Receiver in code

private IntentFilter filter = 
 new IntentFilter(LifeformDetectedReceiver.NEW_LIFEFORM);
private LifeformDetectedReceiver receiver = 
 new LifeformDetectedReceiver();
@Override
public void onResume() {
 super.onResume();
 // Register the broadcast receiver.
registerReceiver(receiver, filter); 
}
@Override
public void onPause() {
 // Unregister the receiver
 unregisterReceiver(receiver);
 super.onPause();
}

Registering Broadcast Receivers in Your Application Manifest

To include a Broadcast Receiver in the 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.

<receiver android:name=”.LifeformDetectedReceiver”>
 <intent-filter>
 <action android:name=”com.paad.alien.action.NEW_LIFEFORM”/>
 </intent-filter>
</receiver>

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.

Leave a Comment