A notification is a message you can display to the user outside of your application’s normal UI. When you tell the system to issue a notification, it first appears as an icon in the notification area. To see the details of the notification, the user opens the notification drawer. Both the notification area and the notification drawer are system-controlled areas that the user can view at any time.
Status bar notifications indicates some ongoing background services such as downloading or playing music or displays an alert/information.To see the notification user needs to open the notification drawer. Notifications are handled by Notification Manger in Android. Notification Manager is a system service used to manage notifications.
To create a status bar notification we need to use two classes, NotificationManager, Notification.
The NotificationManager is a system Service used to manage Notification. Get a reference to it using the getSystemService() method. The syntax is given below –
1 |
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); |
Using the Notification Manager you can trigger new notifications, modify existing ones, or cancel that are no longer required.
You have simple way to create a notification. Follow the following steps in your application to create a notification −
As a first step is to create a notification builder using NotificationCompat.Builder.build(). You will use Notification Builder to set various Notification properties like its small and large icons, title, priority etc.
1 2 |
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( this); |
Once you have Builder object, you can set its Notification properties using Builder object as per your requirement. But this is mandatory to set at least following −
1 2 3 |
mBuilder.setSmallIcon(R.drawable.app_icon_small); mBuilder.setContentTitle("New Message"); mBuilder.setContentText("You've received new message from Androhub."); |
This is an optional part and required if you want to attach an action with the notification. An action allows users to go directly from the notification to an Activity in your application, where they can look at one or more events or do further work.
The action is defined by a PendingIntent containing an Intent that starts an Activity in your application. To associate the PendingIntent with a gesture, call the appropriate method ofNotificationCompat.Builder. For example, if you want to start Activity when the user clicks the notification text in the notification drawer, you add the PendingIntent by calling setContentIntent().
A PendingIntent object helps you to perform an action on your applications behalf, often at a later time, without caring of whether or not your application is running.
We take help of stack builder object which will contain an artificial back stack for the started Activity. This ensures that navigating backward from the Activity leads out of your application to the Home screen.
1 2 3 4 5 6 7 8 9 |
Intent resultIntent = new Intent(MainActivity.this, NotificationActivity.class); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(NotificationActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); |
Finally, you pass the Notification object to the system by calling NotificationManager.notify() to send your notification. Make sure you call NotificationCompat.Builder.build() method on builder object before notifying it. This method combines all of the options that have been set and return a new Notification object.
1 2 3 4 |
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // notificationID allows you to update the notification later on. mNotificationManager.notify(notificationID, mBuilder.build()); |
The NotificationCompat.Builder class allows easier control over all the flags, as well as help constructing the typical notification layouts. Following are few important and most frequently used methods available as a part of NotificationCompat.Builder class.
Method | Description |
---|---|
Notification build() | Combine all of the options that have been set and return a new Notification object. |
NotificationCompat.Builder setAutoCancel (boolean autoCancel) | Setting this flag will make it so the notification is automatically canceled when the user clicks it in the panel. |
NotificationCompat.Builder setContent (RemoteViews views) | Supply a custom RemoteViews to use instead of the standard one. |
NotificationCompat.Builder setContentInfo (CharSequence info) | Set the large text at the right-hand side of the notification. |
NotificationCompat.Builder setContentIntent (PendingIntent intent) | Supply a PendingIntent to send when the notification is clicked. |
NotificationCompat.Builder setContentText (CharSequence text) | Set the text (second row) of the notification, in a standard notification. |
NotificationCompat.Builder setContentTitle (CharSequence title) | Set the text (first row) of the notification, in a standard notification. |
NotificationCompat.Builder setDefaults (int defaults) | Set the default notification options that will be used. |
NotificationCompat.Builder setLargeIcon (Bitmap icon) | Set the large icon that is shown in the ticker and notification. |
NotificationCompat.Builder setNumber (int number) | Set the large number at the right-hand side of the notification. |
NotificationCompat.Builder setOngoing (boolean ongoing) | Set whether this is an ongoing notification. |
NotificationCompat.Builder setSmallIcon (int icon) | Set the small icon to use in the notification layouts. |
NotificationCompat.Builder setStyle (NotificationCompat.Style style) | Add a rich notification style to be applied at build time. |
NotificationCompat.Builder setTicker (CharSequence tickerText) | Set the text that is displayed in the status bar when the notification first arrives. |
NotificationCompat.Builder setVibrate (long[] pattern) | Set the vibration pattern to use. |
NotificationCompat.Builder setWhen (long when) | Set the time that the event occurred. Notifications in the panel are sorted by this time. |
In this tutorial, we are going to learn how to create Single Line Notification and Multi Line Notification in Notification Bar.
1. Create a new project in Eclipse by navigating to File ⇒ New Android ⇒ Application Project and fill required details. By default my activity is MainActivity.java.
2. Open res ⇒ values ⇒ strings.xml and add below string values. This are some strings that i am going to use in this tutorial.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">NotificationBar Demo</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string name="single_line">Single Line Notification</string> <string name="multi_line">Multi Line Notification</string> <string name="start">Start Notification</string> <string name="stop">Stop Notification</string> <string name="update">Update Notification</string> </resources> |
3. Open your AndroidManifest.xml and add the following permission Vibrate permission to make vibrate device when notification occurs .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.notification_bar" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="22" /> <!-- Permission required to vibrate --> <uses-permission android:name="android.permission.VIBRATE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.notification_bar.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> <!-- Notification activity with back navigate task to MainActivity --> <activity android:name=".NotificationActivity" android:label="Details of Notification" android:parentActivityName=".MainActivity" > <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity" /> </activity> </application> </manifest> |
4. Now create a xml layout naming activity_main.xml and add the following views. In this layout i had taken some buttons for both single and multi line notification separately.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:fillViewport="true" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical" android:padding="5dp" > <!-- Single Line Notification Views --> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="15dp" android:text="@string/single_line" android:textColor="#0587d9" android:textSize="20sp" android:textStyle="bold" /> <Button android:id="@+id/start_notificationone" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/start" /> <Button android:id="@+id/stop_notificationone" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/stop" /> <Button android:id="@+id/update_notificationone" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/update" /> <!-- Multi Line Notification Views --> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="15dp" android:text="@string/multi_line" android:textColor="#0587d9" android:textSize="20sp" android:textStyle="bold" /> <Button android:id="@+id/start_notificationtwo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/start" /> <Button android:id="@+id/stop_notificationtwo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/stop" /> <Button android:id="@+id/update_notificationtwo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/update" /> </LinearLayout> </ScrollView> |
5. After creating activity_main.xml create a new xml layout naming notification_activity.xml for pending intent to show notification data in new activity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="center" > <TextView android:id="@+id/show_notificationmessage" android:layout_width="fill_parent" android:layout_height="wrap_content" android:gravity="center" android:padding="5dp" android:textColor="#000000" android:textSize="20sp" /> </LinearLayout> |
6. Now, for creating Multi line notification we have to add the inbox style of notification. For this NotificationCompat.InboxStyle help us to achieve this. In this i had added 6 lines and finally add the inboxstyle to notification builder.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); String[] events = new String[6];// No of lines to show // Loop to add 6 items to array for (int i = 0; i < events.length; i++) events[i] = new String("This is " + i + " line..."); // Sets a title for the Inbox style big view inboxStyle.setBigContentTitle("Big Title Details:"); // Moves events into the big view for (int i = 0; i < events.length; i++) { inboxStyle.addLine(events[i]); } mBuilder.setStyle(inboxStyle); |
7. Open your MainActivity.java and add the following code. I am using two different NotificationId for both Single and MultiLine notification. We will use this ids to start notification, update notification and stop notification. I am also setting a long[] pattern for vibration and also alarm sound for notification.
When user clicks over notification a new activity will open and display a message with current notificationId for this i had put intent values to next intent.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 |
package com.notification_bar; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.RingtoneManager; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.TaskStackBuilder; import android.support.v7.app.AppCompatActivity; import android.support.v7.app.NotificationCompat; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends AppCompatActivity implements OnClickListener { private static Button start, stop, update, start_two, stop_two, update_two; private NotificationManager mNotificationManager;// Notification Manager // Notification id for both Notifications private final int notificationID_SingleLine = 111; private final int notificationID_MultiLine = 222; // No. of messages count for both type of notifications private int numMessages_SingleLine = 0; private int numMessages_MultiLine = 0; private static Uri alarmSound;// Alarm sound uri private final long[] pattern = { 100, 300, 300, 300 };// Vibrate pattern in // long array @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Find all views id start = (Button) findViewById(R.id.start_notificationone); stop = (Button) findViewById(R.id.stop_notificationone); update = (Button) findViewById(R.id.update_notificationone); start_two = (Button) findViewById(R.id.start_notificationtwo); stop_two = (Button) findViewById(R.id.stop_notificationtwo); update_two = (Button) findViewById(R.id.update_notificationtwo); // Implement click listeners start.setOnClickListener(this); stop.setOnClickListener(this); update.setOnClickListener(this); start_two.setOnClickListener(this); stop_two.setOnClickListener(this); update_two.setOnClickListener(this); // Set by default alarm sound alarmSound = RingtoneManager .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); // setting notification manager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); } // Call repersentative methods on buttons press @Override public void onClick(View view) { switch (view.getId()) { case R.id.start_notificationone: displayNotificationSingleLine(); break; case R.id.stop_notificationone: cancelNotificationSingleLine(); break; case R.id.update_notificationone: updateNotificationSingleLine(); break; case R.id.start_notificationtwo: displayNotificationMultiLine(); break; case R.id.stop_notificationtwo: cancelNotificationMultiLine(); break; case R.id.update_notificationtwo: updateNotificationMultiLine(); break; } } /** Single Line Notifications Methods **/ protected void displayNotificationSingleLine() { Log.i("Start", "notification"); /* Invoking the default notification service */ NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( MainActivity.this);// Setting builder mBuilder.setContentTitle("New Message");// title mBuilder.setContentText("You've received new message from Androhub.");// Message mBuilder.setTicker("New Message Alert!");// Ticker mBuilder.setSmallIcon(R.drawable.app_icon_small);// Small icon /* Increase notification number every time a new notification arrives */ mBuilder.setNumber(++numMessages_SingleLine); mBuilder.setSound(alarmSound);// set alarm sound mBuilder.setVibrate(pattern);// set vibration /* Creates an explicit intent for an Activity in your app */ Intent resultIntent = new Intent(MainActivity.this, NotificationActivity.class); resultIntent.putExtra("notificationId", notificationID_SingleLine);// put // notification // id // into // intent resultIntent.putExtra("message", "https://androhub.com");//Your message to show in next activity // Task builder to maintain task for pending intent TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(NotificationActivity.class); /* Adds the Intent that starts the Activity to the top of the stack */ stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);// Set flag to update current mBuilder.setContentIntent(resultPendingIntent);// set content intent /* notificationID allows you to update the notification later on. */ mNotificationManager .notify(notificationID_SingleLine, mBuilder.build()); } protected void cancelNotificationSingleLine() { Log.i("Cancel", "notification"); mNotificationManager.cancel(notificationID_SingleLine);// Cancel the // notification // id // notification // if it is // showing } protected void updateNotificationSingleLine() { Log.i("Update", "notification"); /* Invoking the default notification service */ NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( this); mBuilder.setContentTitle("Updated Message"); mBuilder.setContentText("You've got updated message from Androhub."); mBuilder.setTicker("Updated Message Alert!"); mBuilder.setSmallIcon(R.drawable.app_icon_small); mBuilder.setSound(alarmSound); mBuilder.setVibrate(pattern); /* Increase notification number every time a new notification arrives */ mBuilder.setNumber(++numMessages_SingleLine); /* * Creates an explicit * intent for an Activity in * your app */ Intent resultIntent = new Intent(this, NotificationActivity.class); resultIntent.putExtra("notificationId", notificationID_SingleLine); resultIntent.putExtra("message", "https://androhub.com"); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(NotificationActivity.class); /* Adds the Intent that starts the Activity to the top of the stack */ stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); /* Update the existing notification using same notification ID */ mNotificationManager .notify(notificationID_SingleLine, mBuilder.build()); } /** ---------------------------------------------------------------------- **/ /** Multi Line Notifications Methods **/ protected void displayNotificationMultiLine() { Log.i("Start", "notification"); /* Invoking the default notification service */ NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( this); mBuilder.setContentTitle("New Message"); mBuilder.setContentText("You've received new message from Androhub."); mBuilder.setTicker("New Multi Message Alert!"); mBuilder.setSmallIcon(R.drawable.app_icon_small); /* Increase notification number every time a new notification arrives */ mBuilder.setNumber(++numMessages_MultiLine); mBuilder.setSound(alarmSound); mBuilder.setVibrate(pattern); /* Add Big View Specific Configuration */ NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); String[] events = new String[6];// No of lines to show // Loop to add 6 items to array for (int i = 0; i < events.length; i++) events[i] = new String("This is " + i + " line..."); // Sets a title for the Inbox style big view inboxStyle.setBigContentTitle("Big Title Details:"); // Moves events into the big view for (int i = 0; i < events.length; i++) { inboxStyle.addLine(events[i]); } mBuilder.setStyle(inboxStyle); /* Creates an explicit intent for an Activity in your app */ Intent resultIntent = new Intent(this, NotificationActivity.class); resultIntent.putExtra("notificationId", notificationID_MultiLine); resultIntent.putExtra("message", "https://androhub.com"); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(NotificationActivity.class); /* Adds the Intent that starts the Activity to the top of the stack */ stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); /* notificationID allows you to update the notification later on. */ mNotificationManager.notify(notificationID_MultiLine, mBuilder.build()); } protected void cancelNotificationMultiLine() { Log.i("Cancel", "notification"); mNotificationManager.cancel(notificationID_MultiLine); } protected void updateNotificationMultiLine() { Log.i("Start", "notification"); /* Invoking the default notification service */ NotificationCompat.Builder mBuilder = new NotificationCompat.Builder( this); mBuilder.setContentTitle("New Message"); mBuilder.setContentText("You've got updated message from Androhub."); mBuilder.setTicker("New Multi Message Alert!"); mBuilder.setSmallIcon(R.drawable.app_icon_small); /* Increase notification number every time a new notification arrives */ mBuilder.setNumber(++numMessages_MultiLine); mBuilder.setSound(alarmSound); mBuilder.setVibrate(pattern); /* Add Big View Specific Configuration */ NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle(); String[] events = new String[6]; // Loop to add 6 items to array for (int i = 0; i < events.length; i++) events[i] = new String("This is update of " + i + " line..."); // Sets a title for the Inbox style big view inboxStyle.setBigContentTitle("Big Title Details"); // Moves events into the big view for (int i = 0; i < events.length; i++) { inboxStyle.addLine(events[i]); } mBuilder.setStyle(inboxStyle); /* Creates an explicit intent for an Activity in your app */ Intent resultIntent = new Intent(this, NotificationActivity.class); resultIntent.putExtra("notificationId", notificationID_MultiLine); resultIntent.putExtra("message", "https://androhub.com"); TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(NotificationActivity.class); /* Adds the Intent that starts the Activity to the top of the stack */ stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); /* notificationID allows you to update the notification later on. */ mNotificationManager.notify(notificationID_MultiLine, mBuilder.build()); } /** ---------------------------------------------------------------------- **/ } |
8. Finally create a new activity naming NotificationActivity.java this activity open when user clicks over notification. In this activity i am getting notificationId and message and displaying it over textview.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
package com.notification_bar; import android.app.NotificationManager; import android.content.Context; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.text.util.Linkify; import android.widget.TextView; public class NotificationActivity extends AppCompatActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.notification_activity); String message = ""; int id = 0; Bundle extras = getIntent().getExtras();// get intent data if (extras == null) { // If it is null then show error message = "error"; } else { // get id and message id = extras.getInt("notificationId"); message = extras.getString("message"); } TextView text = (TextView) findViewById(R.id.show_notificationmessage); message = "Notification Id : " + id + "n Message : " + message;// Concat // id // and // message text.setText(message);// set text Linkify.addLinks(text, Linkify.ALL);// Linkify textview for phone // numbers, url ,etc. NotificationManager myNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); // remove the notification with the specific id myNotificationManager.cancel(id); } } |
9. Now, you are all done, run your app and you will get the output as shown in video.
Thanks.
Subscribe to us and get the latest news.