Android BroadcastReceiver – Create | Register examples

Android BroadcastReceiver – Create-Register examples

An Android BroadcastReceiver is another component in Android process, along with activities, content provider, and Services.

It is a component that can respond to a broadcast message sent by a client.

The message itself is an Android broadcast intent. A broadcast intent (message) can invoke more than one receiver.

A component such as an activity or a service uses the sendBroadcast() method available on the Context class to send a broadcast event.

Receiving components of the broadcast intent will need to inherit from a receiver class.

These receiving components need to be registered in the manifest file through a receiver tag to indicate that the class is interested in responding to a certain type of broadcast intent.

Create Android BroadcastReceiver class

public class MyReceiver extends BroadcastReceiver
{
 @Override
  public void onReceive(Context context, Intent intent) {
  // TODO Auto-generated method stub
  }
}

Register Android BroadcastReceiver

A receiver can be registered via the AndroidManifest.xml file.

Alternatively to this static registration, you can also register a receiver dynamically via the Context.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.

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

Registering and Unregistering Android Broadcast Receiver in Code:

private IntentFilter filter = new IntentFilter(MyReceiver.ACTION);
private MyReceiver receiver = new MyReceiver();

@Override
public void onResume()

{
 super.onResume();
 //Register the broadcast receiver.
 registerReceiver(receiver, filter);
}

@Override
public void onPause()
{
 //Unregister the receiver
 unregisterReceiver(receiver);
 super.onPause();
}

System generated Events

Some system generated events are as follows:

android.intent.action.BATTERY_CHANGED

It describes Sticky broadcast containing the charging state, level, and other information about the battery.

android.intent.action.BATTERY_LOW

It Indicates low battery condition on the device.

android.intent.action.BOOT_COMPLETED

This is broadcast one time after the system has finished booting.

android.intent.action.CALL

It performs a call to someone specified by the data.

android.intent.action.REBOOT

It describes the device is reboot.