Broadcast Receivers simply respond to broadcast messages from other applications or from the system itself. It receives Action. Action can be –
- User defined /created by developer /Broadcasted by developer
- System defined /pre-defined /Broadcasted by android system
Example :
In this example, there is a Receiver (Receiver.java) which receives broadcast actions which are defined in its Intent filter . Actions defined in Intent filter on BroadcastReceiver can be any ; it may be user defined or system defined. In the given example, there is an action named “action1“. When this action is triggered, Receiver.class will receive the broadcast message and notification is displayed.
In AndroidManifest.xml , intent filter of Receiver.java is as under:
<receiver android:name=".Receiver" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="action1" />
</intent-filter>
</receiver>
MainActivity.java whose title is “Receiver”
//Here in this activity ,there's a button ,by clicking on that "action1" is triggered and Receiver will receive broadcast message.
public void onClick(View v){
Intent i=new Intent("action1");
sendBroadcast(i);
}
Receiver.java
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
if(action.equals("action1")){
Toast.makeText(context,"Action1 is triggered",Toast.LENGTH_SHORT).show();
NotificationCompat.Builder builder=new NotificationCompat.Builder(context);
//ActivityDemo starts when "ADD" option in notification is clicked
Intent i=new Intent(context,ActivityDemo.class);
PendingIntent pi=PendingIntent.getActivity(context,1001,i,0);
//Call Intent - By clicking on "CALL" icon , keypad will open and the specified mobile number will be automatically written
Intent call=new Intent(Intent.ACTION_DIAL);
call.setData(Uri.parse("tel:924xxxxxxx"));
PendingIntent piCall=PendingIntent.getActivity(context,101,call,0);
builder.setContentIntent(pi);
builder.setDefaults(Notification.DEFAULT_ALL);
builder.setSmallIcon(R.drawable.music);
builder.setContentTitle("Title");
builder.setContentText("This is a notification.");
builder.setStyle(new NotificationCompat.BigTextStyle().bigText("This is a big text .This text gives complete information in multiple lines."));
builder.addAction(android.R.drawable.ic_menu_add, "Add", pi);
builder.addAction(android.R.drawable.ic_menu_call, "Call", piCall);
Notification notification=builder.build();
NotificationManager manager=(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
manager.notify(100,notification);
}
}
}

MainActivity

Notification