Thursday, October 24, 2013

Android BroadcastReceiver Tutorial

Using BroadcastReceivers in Android
This tutorial describes how to create and consume Android services. It is based on Eclipse 4.3, Java 1.6 and Android 4.2.

1. Broadcast receiver

1.1. Definition

broadcast receiver (short receiver) is an Android component which allows you to register for system or application events. All registered receivers for an event will be notified by the Android runtime once this event happens.
For example applications can register for the ACTION_BOOT_COMPLETED system event which is fired once the Android system has completed the boot process.

1.2. Implementation

A receiver can be registered via the AndroidManifest.xml file.
Alternatively to this static registration, you can also register a broadcast receiver dynamically via theContext.registerReceiver() method.
The implementing class for a receiver extends the BroadcastReceiver class.
If the event for which the broadcast receiver has registered happens the onReceive() method of the receiver is called by the Android system.

1.3. Lifecycle of a broadcast receiver

After the onReceive() of the BroadcastReceiver has finished, the Android system can recycle the BroadcastReceiver.
Before API11 you could not perform any asynchronous operation in the onReceive() method because once the onReceive() method is finished the Android system was allowed to recyled that component. If you have potentially long running operations you should trigger a service for that.
As for API11 you can call the goAsync() method. If this method was called it returns an object of thePendingResult type. The Android system considers the receiver as alive until you call thePendingResult.finish() on this object. With this option you can trigger asynchronous processing in a receiver. As soon as that thread has completed its task is calls finish() to indicate to the Android system that this component can be recycled.

1.4. Restrictions for defining broadcast receiver

As of Android 3.1 the Android system will by default exclude all BroadcastReceiver from receivingintents if the corresponding application has never been started by the user or if the user explicitly stopped the application via the Android menu (in Manage Application).
This is an additional security features as the user can be sure that only the applications he started will receive broadcast intents.

2. System broadcasts

Several system events are defined as final static fields in the Intent class. Other Android system classes also define events, e.g. the TelephonyManager defines events for the change of the phone state.
The following table lists a few important system events.
Table 1. System Events
EventDescription
Intent.ACTION_BOOT_COMPLETEDBoot completed. Requires theandroid.permission.RECEIVE_BOOT_COMPLETEDpermission.
Intent.ACTION_POWER_CONNECTEDPower got connected to the device.
Intent.ACTION_POWER_DISCONNECTEDPower got disconnected to the device.
Intent.ACTION_BATTERY_LOWBattery gets low, typically used to reduce activities in your app which consume power.
Intent.ACTION_BATTERY_OKAYBattery status good again.


3. Automatically starting Services from a Receivers

To start Services automatically after the Android system starts you can register aBroadcastReceiver to the Android android.intent.action.BOOT_COMPLETED system event. This requires the android.permission.RECEIVE_BOOT_COMPLETED permission.
The following AndroidManifest.xml registers a receiver for the BOOT_COMPLETED event.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.vogella.android.ownservice.local"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="10" />

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name=".ServiceConsumerActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<receiver android:name="MyScheduleReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name="MyStartServiceReceiver" >
</receiver>
</application>

</manifest>
In the onReceive() method the corresponding BroadcastReceiver would then start the service.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, WordService.class);
context.startService(service);
}
}
If you application is installed on the SD card, then it is not available after theandroid.intent.action.BOOT_COMPLETED event. Register yourself in this case for theandroid.intent.action.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE event.
Also note that as of Android 3.0 the user needs to have started the application at least once before your application can receive android.intent.action.BOOT_COMPLETED events.

4. Pending Intent

A PendingIntent is a token that you give to another application (e.g. Notification Manager, Alarm Manager or other 3rd party applications), which allows this other application to use the permissions of your application to execute a predefined piece of code.
To perform a broadcast via a pending intent so get a PendingIntent via the getBroadcast() method of the PendingIntent class. To perform an activity via an pending intent you receive the activity viaPendingIntent.getActivity().

5. Tutorial: Broadcast Receiver

We will define a broadcast receiver which listens to telephone state changes. If the phone receives a phone call then our receiver will be notified and log a message.
Create a new project de.vogella.android.receiver.phone. Create a dummy activity as this is required so that the BroadcastReceiver also gets activated. Create the following AndroidManifest.xmlfile.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.vogella.android.receiver.phone"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="15" />

<uses-permission android:name="android.permission.READ_PHONE_STATE" >
</uses-permission>

<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<receiver android:name="MyPhoneReceiver" >
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" >
</action>
</intent-filter>
</receiver>
</application>



</manifest>
Create the MyPhoneReceiver class.
package de.vogella.android.receiver.phone;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;

public class MyPhoneReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
String state = extras.getString(TelephonyManager.EXTRA_STATE);
Log.w("MY_DEBUG_TAG", state);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
String phoneNumber = extras
.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.w("MY_DEBUG_TAG", phoneNumber);
}
}
}
}
Install your application and simulate a phone call via the DDMS perspective in Eclipse. Your receiver is called and logs a message to the console.

6. Tutorial: System Services and BroadcastReceiver

In this chapter we will schedule a broadcast receiver via the AlertManager. Once called it will use the VibratorManager and a Toast to notify the user.
Create a new project called de.vogella.android.alarm with the activity called AlarmActivity.
Create the following layout.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<EditText
android:id="@+id/time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Number of seconds"
android:inputType="numberDecimal" >
</EditText>

<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="startAlert"
android:text="Start Counter" >
</Button>

</LinearLayout>
Create the following broadcast receiver class. This class will get the Vibrator service.
package de.vogella.android.alarm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Vibrator;
import android.widget.Toast;

public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Don't panik but your time is up!!!!.",
Toast.LENGTH_LONG).show();
// Vibrate the mobile phone
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
}

}
Maintain this class as broadcast receiver in AndroidManifest.xml and allow the vibrate authorization.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.vogella.android.alarm"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="15" />

<uses-permission android:name="android.permission.VIBRATE" >
</uses-permission>

<application
android:icon="@drawable/icon"
android:label="@string/app_name" >
<activity
android:name=".AlarmActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<receiver android:name="MyBroadcastReceiver" >
</receiver>
</application>

</manifest>
Change the code of your Activity "AlarmActivity" to the following. This activity will create an Intent for the Broadcast receiver and get the AlarmManager service.
package de.vogella.android.alarm;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class AlarmActivity extends Activity {

/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

public void startAlert(View view) {
EditText text = (EditText) findViewById(R.id.time);
int i = Integer.parseInt(text.getText().toString());
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (i * 1000), pendingIntent);
Toast.makeText(this, "Alarm set in " + i + " seconds",
Toast.LENGTH_LONG).show();
}

}
Run your application on the device. Set your time and start the alarm. After the defined number of seconds a Toast should be displayed. Keep in mind that the vibrator alarm does not work on the Android emulator.
Alarm application running

7. Defining custom events and receivers

7.1. Registering broadcast receiver for custom events

You can register a receiver for your own customer actions.
The following AndroidManifest.xml file shows a broadcast receiver which is registered to a custom action.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="de.vogella.android.receiver.own"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="15" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

<receiver android:name="MyReceiver" >
<intent-filter>
<action android:name="de.vogella.android.mybroadcast" />
</intent-filter>
</receiver>
</application>

</manifest>

7.2. Sending broadcast intents

The sendBroadcast() method from the Context class allows you to send intents to your registered receivers. The following coding show an example.
Intent intent = new Intent();
intent.setAction("de.vogella.android.mybroadcast");
sendBroadcast(intent);
You cannot trigger system broadcasts events, the Android system will prevent this.

Tip

The receivers are called asynchronous, i.e. the sendBroadcast() method return immediately and does not wait that the receivers have executed.

7.3. Local broadcast events with LocalBroadcastManager

The LocalBroadcastManager class is used to register for and send broadcasts of Intents to local objects within your process. This is faster and more secure as your events don't leave your application.
The following example shows an activity which registers for a customer event called my-event.
@Override
public void onResume() {
super.onResume();

// Register mMessageReceiver to receive messages.
LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver,
new IntentFilter("my-event"));
}

// handler for received Intents for the "my-event" event
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Extract data included in the Intent
String message = intent.getStringExtra("message");
Log.d("receiver", "Got message: " + message);
}
};

@Override
protected void onPause() {
// Unregister since the activity is not visible
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
super.onPause();
}
// This method is assigned to button in the layout
// via the onClick property
public void onClick(View view) {
sendMessage();
}

// Send an Intent with an action named "my-event".
private void sendMessage() {
Intent intent = new Intent("my-event");
// add data
intent.putExtra("message", "data");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
}

8. Dynamic broadcast receiver registration

8.1. Dynamically registered receiver

You can register a receiver dynamically via the Context.registerReceiver() method. You can also dynamically unregister receiver by using Context.unregisterReceiver() method.

Warning

Do not forget to unregister a dynamically registered receiver by usingContext.unregisterReceiver() method. Otherwise the system will report a leaked broadcast receiver error. For instance if you registered a receive in onResume() methods of your activity, you should unregister it in the onPause() method.

8.2. Using the package manager to disable static receivers

You can use the PackageManager class to enable or disable receivers registered in yourAndroidManifest.xml file.
ComponentName receiver = new ComponentName(context, myReceiver.class);
PackageManager pm = context.getPackageManager();

pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);

8.3. Sticky broadcast intents

A normal broadcast intent is not available anymore after is was send and processed by the system. If you use the sendStickyBroadcast(Intent) method, the corresponding intent is sticky, meaning the intent you are sending stays around after the broadcast is complete.
You can retrieve that data through the return value ofregisterReceiver(BroadcastReceiver, IntentFilter) . This works also for a nullBroadcastReceiver.
In all other ways, this behaves the same as sendBroadcast(Intent).
The Android system uses sticky broadcast for certain system information. For example the battery status is send as sticky Intent and can get received at any time. The following example demonstrates that.
// Register for the battery changed event
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);

/ Intent is sticky so using null as receiver works fine
// return value contains the status
Intent batteryStatus = this.registerReceiver(null, filter);

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING
|| status == BatteryManager.BATTERY_STATUS_FULL;

boolean isFull = status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
Sticky broadcast intents typically require special permissions.

No comments:

Post a Comment