Android notifications example

What is android notifications?

Definition from Android developers site:

A status notification adds an icon to the system’s status bar (with an optional ticker-text message) and a notification message in the notifications window. When the user selects the notification, Android fires an Intent that is defined by the Notification(usually to launch an Activity). You can also configure the notification to alert the user with a sound, a vibration, and flashing lights on the device.

What are we going to develop?

The application which we are going to develop will have two buttons – one to trigger notification and other to clear the triggered notification.

Notification message will be created when you click on the ‘Raise notification’ button. When you select the notification, it will take you to another activity. If you wish to clear the notification created, click on ‘Cancel notification’ button.

[pgsubscribe]

You have to remember two things when you think about android notifications:

  1.  Notification should be triggered by one activity.
  2. On clicking the notification from status bar, it should take the user to another activity or same activity.

Consider this scenario: Unread messages in your android mobile will be shown in the notification status bar. On clicking it, you will be taken to the messagebox.

I hope you got the meaning 🙂

Quick Links

Project Structure

  • Create new android project [File >> New >> Android Project] with project name AndroidNotificationsExample
  • Click next and select target android device version [I chose version 2.2]
  • Click next and enter package name – ‘com.prgguru.android’
  • Click finish

Code Listings

Layout creation:

Layout XML for this application should look like below:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <Button android:id="@+id/notify"
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent" 
      android:layout_weight="1"
      android:text="Trigger notification"
      android:onClick="triggerNotification"
      />
  <Button android:id="@+id/cancel"
      android:layout_width="fill_parent" 
      android:layout_height="fill_parent" 
      android:layout_weight="1"
      android:text="Cancel notification"
      android:onClick="clearNotification"
      />
</LinearLayout>

Layout design should look like:

Create following variables and object under Activity class:

//Notification message ID
 private static final int NOTIFY_ME_ID=1337;
//Counter
 private int count=0;
//Create NotificationManager  object
 private NotificationManager notifyMgr=null;

Iniside onCreate method, assign notifyMgr object with the handler to handle system level notifications service:

notifyMgr=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);

Methods triggerNotification and clearNotifications will be created to trigger and clear notifications. These methods are already declared for the button onClick event in main.xml. Take a look at the lines 12 and 19 of layout xml.

Create triggerNotification method to create notification:

public void triggerNotification(View v) {
//Instantiate notification with icon and ticker message 
Notification notifyObj=new Notification(R.drawable.telephone,
                                        "Notification message!",
                                        System.currentTimeMillis());
//PendingIntent to launch our activity if the user selects it 
PendingIntent i=PendingIntent.getActivity(this, 0,
                            new Intent(this, NotifyActivity.class),
                                              0);
//Set the info that show in the notification panel    
notifyObj.setLatestEventInfo(this, "Notification Created",
                            "Click here to see the message", i);
//Value indicates the current number of events represented by the notification
notifyObj.number=++count;
//Set default vibration
notifyObj.defaults |= Notification.DEFAULT_VIBRATE;
//Set default notification sound
notifyObj.defaults |= Notification.DEFAULT_SOUND;
//Clear the status notification when the user selects it
notifyObj.flags|=Notification.FLAG_AUTO_CANCEL;    
//Send notification
notifyMgr.notify(NOTIFY_ME_ID, notifyObj);
  }

Create clearNotification method to clear notification:

 public void clearNotification(View v) {
 //Clear the notification 
notifyMgr.cancel(NOTIFY_ME_ID);
 }

Did you notice ‘NotifyActivity’ class in line no 7 of triggerNotification method above?. We are yet to create ‘NotifyActivity’ class which is an another activity which will be started when user clicks on the notification.

package com.prgguru.android;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class NotifyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Create textview
TextView txt=new TextView(this); 
//Set text
 txt.setText("You have successfully opened the activity associated with the notification!");
//Set textview on the view
setContentView(txt);
}
}

Add the activity(NotifyActivity) in AndroidManifest.xml:

<activity android:label="@string/app_name"
              android:name=".NotifyActivity"></activity>

Add notification icon(warning.png) under /res/drawable-hdpi folder [right click on the image and save]:

[pglinkadssmall1]

Demo

We are done with the development, yet to test the application.

Right click on the project >> Run As >> Android Application >> Choose emulator or Android device



Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse &gt;&gt; File &gt;&gt; Import.. &gt;&gt; Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android is the installation file simliar to exe in windows.

[pglinkadssmall]

Reference

Android Notifications

Suggested posts for further reading


[pgfeedback]
[pgwriteforus]

Related Articles

Author: Udhay

Share This Post On
468 ad
  • stanks

    triggerNotification method -> line 3 -> notify to notifyObj?

    • It has been changed. Thanks for noticing it! 🙂

  • Prash….

    Thanks, its really helpful for me.

  • prakash

    I throws me illegal state exception could not execut method activity

    • Please debug and see where you are getting illegal state exception.

  • zeptus

    Hey there, great tutorials, really interesting and useful..
    I’m new to android development and I’m facing problems in connecting a database to my application, I’m clueless… Can you offer me any clear solutions ? I’ve set the layout for registration and log in pages and few other static pages but I need to know how to create the databases ( I have some knowledge in php, and I’m using a local wamp server).
    Sorry for bothering… Any help will be much appreciate it.
    Thank you in advance.

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares