Show Notification when Air-plane mode change (Using Broadcast Receiver)

Hello guys!

Today I have a simple example code that demonstrate the use of Broadcast Receiver in Android, this tutorial also help you to understand how to show a Notification.

Ok now we start this example.

Step 1: Create a new class named “BroadCastRec” which is extended from BroadCastReceiver class:

public class BroadCastRec extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
sendNotification(context, "From broadcast", MainActivity.notificationID);
}

private void sendNotification(Context c, String msg, int id) {
PendingIntent contentIntent = PendingIntent.getActivity(c, 0,
new Intent(c, SecondActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
c).setSmallIcon(android.R.drawable.btn_star)
.setContentTitle("Title for notification")
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg)
.setContentIntent(contentIntent);

Notification notification = mBuilder.build();
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_SOUND;
NotificationManager manager = (NotificationManager) c.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(id, notification); // mBuilder.build()

}
}

Step 2: Declare this receiver in manifest, notice the action name:

<receiver android:name=”com.example.admin.broadcastreceiver.BroadCastRec”>
<intent-filter>
<action android:name=”android.intent.action.AIRPLANE_MODE”/>
</intent-filter>
</receiver>

 

Step 3: MainActivity.java:

 

public class MainActivity extends Activity {
public static int notificationID = 100;
BroadCastRec receiver;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiver = new BroadCastRec();
}
}

Now let’s run our program on physical device and then try to change Air-plane mode.

Good luck!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s