A Notification is a message displayed to the user outside of your application’s normal UI. It informs the user about the event that occured which requires attention. Examples for notification are alarm clocks, SMS indicators, birthday reminders etc. A service running in the background cannot intrude an Activity in the foreground to inform about any event since the Activity has highest priority, So Android provides a notification system which notifies the user in the form of a status bar icon which can steer to another activity, a toast message or any kind of hardware alert.
Notifications can display once or any number of times. A notification in the status bar appears as an icon and some short text. When the status bar is pulled down, the user can see more notification details.
Available notifications are,
- Flash Lights
- Play sound
- Status bar icons
- Mobile phone vibrations
Steps to create a Notification in Android
Step 1: Creating a status bar notification
In the below code we create a notification object.
Notification notification=new Notification(R.drawable.icon,"Saanvi Birthday!", System.currentTimeMillis());
Here we have passed three parameters ,
- int icon-we set the icon to one of the system icons.
- The ticker text displayed briefly in the status bar.
- The time-to show the user when the notification occurred.
Step 2: Customizing expanded View
notification.setLatestEventInfo(this, "Reminder: Saanvi Birthday", "Today is your friend Saanvi's Birthday, please wish her", null);
The above code is used to customize the notification’s expand view. The expanded view contains a notification title and a text(Notification message) that tells the user about the notification.
Step 3: Passing a pendingIntent
PendingIntent: PendingIntent wraps the regular intent inside an object.This is the intent that can be fired at a later point of time. In our case the pendingIntent Intent(StartActivity) is fired when the user clicks on the Notification.
Intent intent=new Intent(getApplicationContext(), SecondActivity.class); PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(), 0, intent, 0); notification.setLatestEventInfo(this, "Reminder: Saanvi Birthday", "Today is your friend Saanvi's Birthday, please wish her", pendingIntent);
In the above code the activity “SecondActivity” is fired when the user clicks on the expanded view of the notification.
Step 4: Triggering the Notification via NotificationManager
NotificationManager is a system service. To create notification we use the NotificationManager class which can be retrieved from the Activity via the getSystemService() method. The NotificationManager has following methods,
- notify(int,Notification)
- This is used to trigger a particular notification which is identified by the first parameter “Notification ID”,
- cancel(int)
- This is used to cancel a particular notification by passing notification Id.
- cancelAll()
- Used to cancel all notifications.
The notification is triggered as below
private static final int NOTIFICATION_ID=1; final NotificationManager mgr=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); mgr.notify(NOTIFICATION_ID,notification);
So far we have seen the steps to create a notification. Let us now look at a simple example of creating a notification in Android 2.2
Required layouts:
- main.xml
- second.xml
Required Activities:
- Activity_Notification.java
- SecondActivity.java(Which is fired when the user clicks on the notification’s expanded view)
Working of this example:
The layout main.xml contains two buttons named “start” and “clear”. Start button to create a notification and clear buton to clear the notification. To see the created notification you have to swipe your finger down from the top of the screen. Inorder to respond to the notification, you have to touch it. Then the second activity “Second_Activity” is fired up. Follow the below steps to create the example.
Step 1: Set up the android working environment
To know about how to set up a working environment, please refer to the post Set up environment.
Step 2: Create an android project
Create an android project named “NotificationDemo” with the activity “Activity_Notification.java”. To know how to create an android project, please refer to the post create an android project.
Step 3: Create the required layouts
As I said earlier I will be using two layouts main.xml and second.xml. If you have any doubts on how to create a layout xml file, please refer to one of our earlier posts Create a layout.
Open the main.xml which gets created automatically when you create your project, and paste the below code.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout android:id="@+id/RelativeLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="<a href="http://schemas.android.com/apk/res/android">http://schemas.android.com/apk/res/android</a>"> <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Notification Demo" android:layout_centerHorizontal="true" android:layout_marginTop="30dip" android:textStyle="bold"></TextView> <Button android:layout_below="@id/TextView01" android:layout_width="wrap_content" android:text="Start" android:id="@+id/start" android:layout_centerHorizontal="true" android:layout_height="50dip" android:layout_marginTop="20dip"></Button> <Button android:layout_width="wrap_content" android:text="Clear" android:layout_below="@+id/start" android:id="@+id/clear" android:layout_centerHorizontal="true" android:layout_height="50dip" android:layout_marginTop="20dip"></Button> </RelativeLayout>
You can always pass the pendingIntent null if you are not willing to start a second activity on click of the notification. If you want to do something then you need to create second.xml layout file. I would be creating second.xml for your reference to show how a pendingIntent works.
Open second.xml and paste the below code. Here I would just include a textview which just says you have clicked on notification.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="<a href="http://schemas.android.com/apk/res/android"> http://schemas.android.com/apk/res/android</a>" android:layout_width="wrap_content" android:layout_height="wrap_content"> <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="You just clicked on a notification"></TextView> </LinearLayout>
Step 4: Create the required activities
Here in this example I would be using the activity “Activity_Notification.java” and “SecondActivity.java”.
Open Activity_Notification.java and paste the below code.
package my.app; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class Activity_Notification extends Activity { Button start,clear; Notification notification; private static final int NOTIFICATION_ID=1; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); start=(Button)findViewById(R.id.start); clear=(Button)findViewById(R.id.clear); final NotificationManager mgr=(NotificationManager)getSystemService(NOTIFICATION_SERVICE); notification=new Notification(R.drawable.icon,"Saanvi Birthday!", System.currentTimeMillis()); //Intent to start new activity on click of expanded view Intent intent=new Intent(getApplicationContext(), SecondActivity.class); PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(), 0, intent, 0); notification.setLatestEventInfo(this, "Reminder: Saanvi Birthday", "Today is your friend Saanvi's Birthday, please wish her", pendingIntent); start.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub //to notify the user mgr.notify(NOTIFICATION_ID,notification); } }); clear.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub //to clear the notification mgr.cancel(NOTIFICATION_ID); } }); } }
Create a new activity “SecondActivity.java”. If you are not familiar with creating a new activity, please go through the post Create a Activity.
package my.app; import android.app.Activity; import android.os.Bundle; public class SecondActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.second); } }
If you want to do nothing on click of notification’s view, just pass the intent object as null to the PendingIntent method as below.
PendingIntent pendingIntent=PendingIntent.getActivity(getApplicationContext(), 0, null, 0);
Please make a note that passing a pendingIntent object to setLatestEventInfo() method is a must failing which you will get a force close. If you don’t want to do anything on click of notification, just pass the intent object null.
Step 5: Declare the Activities in manifest file
Your first activity “Activity_Notification” would be automatically declared when you create your application. Declare the second activity “SecondActivity”. If you want to know more about AndroidManifest.xml, please refer to the post manifest.
Now your manifest file contains the below code.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="<a href="http://schemas.android.com/apk/res/android"> http://schemas.android.com/apk/res/android</a>" package="my.app" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".Activity_Notification" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="SecondActivity"></activity> </application> <uses-sdk android:minSdkVersion="8" /> </manifest>
Step 6: Run your application
Select your project ->right click->Run As->Android application
Now your first activity gets fired up as below.
Click the highlighted “Start” button to raise the notification. Your notification fires up as below.
Swipe your finger down from the top of the screen. You can now see your notification’s expanded view as below.
Android provides you a default “Clear” button to clear the notification or you can clear it programmatically using cancel() method of Notification Manager. Click on the notification to start a new activity SecondActivity.java”.
If you don’t want to start the new activity just click the “Clear” button in the first image, which clears the Notification as below.
This is how you can raise and clear the notifications in android. If you have any issues regarding this article, please post it in comment section. I hope this article would have provided more detailed explanation on how to create a notification using the NotificationManager API and create a sample application. If you have any questions, please post it in the comments section.