NOTE:

NOTE: Of late, I have been getting requests for very trivial problems that many of you are facing in your day-to-day work. This blog is not to solve your "project" problems - surely not a "Support" site.
I just love to share my knowledge in my spare time and would appreciate any questions or feedback on the articles and code I have shared. I also do appreciate thought-provoking questions that would lead me to write more articles and share.
But please do not put your day-to-day trivial problems here. Even if you do, you most probably would not get a response here.
Thanks

Search This Blog

x

Wednesday 2 September 2009

Notifications - Android Tutorial for Beginners (Part 6)


We have seen Activities and Intents. Now we need to move on to services. However, since services mostly interact with a user through notifications, I felt the need to introduce a simple program to deal with Notifications.


What are Notifications? The name itself implies their functionality. They are a way of alerting a user about an event that he needs to be informed about or even take some action on getting that information.


Notification on Android can be done in any of the following ways:
  • ·         Status Bar Notification
  • ·         Vibrate
  • ·         Flash lights
  • ·         Play a sound

From the Notification, you can allow the user to launch a new activity as well. Now we will look at status bar notification as this can be easily tested on the emulator.


To create a status bar notification, you will need to use two classes: Notification and NotificationManager.
  • ·         Notification – defines the properties of the status bar notification like the icon to display, the test to display when the notification first appears on the status bar and the time to display.
  • ·         NotificationManager is an android system service that executes and manages all notifications. Hence you cannot create an instance of the NotificationManager but you can retrieve a reference to it by calling the getSystemService() method.

Once you procure this handle, you invoke the notify() method on it by passing the notification object created.


So far, you have all the information to display on the status bar. However, when the user clicks the notification icon on the status bar, what detailed information should you show the user? This is yet to be created. This is done by calling the method setLatestEventInfo() on the notification object. What needs to be passed to this method, we will see with an example.


You can download the code for a very simple Notification example here:


The code is explained below:


Step 1: Procure a handle to the NotificationManager:


            private NotificationManager mNotificationManager;
      …
mNotificationManager =
      (NotificationManager)getSystemService(NOTIFICATION_SERVICE);


Step 2: Create a notification object along with properties to display on the status bar


final Notification notifyDetails =
new Notification(R.drawable.android,"New Alert, Click Me!",System.currentTimeMillis());



Step 3: Add the details that need to get displayed when the user clicks on the notification. In this case, I have created an intent to invoke the browser to show the website http://www.android.com


Context context = getApplicationContext();
     
CharSequence contentTitle = "Notification Details...";
     
CharSequence contentText = "Browse Android Official Site by clicking me";
Intent notifyIntent = new Intent(android.content.Intent.ACTION_VIEW,Uri.parse("http://www.android.com"));
     
PendingIntent intent =
      PendingIntent.getActivity(SimpleNotification.this, 0,
      notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);
Step 4: Now the stage is set. Notify.
       
      mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);


Note that all of the above actions(except getting a handle to the NotificationManager) are done on the click of a button “Start Notification”. So all the details go into the setOnClickListener() method of the button.
Similarly, the notification, for the example sake is stopped by clicking a cancel notification button. And the code there is :
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);


Now, you may realize that the constant SIMPLE_NOTIFICATION_ID becomes the way of controlling, updating, stopping a current notification that is started with the same ID.


For more options like canceling the notification once the user clicks on the notification or to ensure that it does not get cleared on clicking the “Clear notifications” button, please see the android reference documentation

82 comments:

  1. At last I found a treasure chest dedicated for android .Your post is vivid and the style of presentation with simple english is appreciable,suitable for Indian readers like me .This post has really made me breath easy, reading docs alone for understanding Android could be a hell task.I wish a note on Pending Intents too.
    Ganesh

    ReplyDelete
  2. Ganesh,
    What is it that you are looking for in Pending Intent? If you see the notification example, a PendingIntent object has been created to launch a new activity from the Notification status.
    Here the PendingIntent.getActivity(..) creates an intent that can be passed on to another activity which uses the intent.

    ReplyDelete
  3. thanx for this help, bt i want to minimize my running application on button click event......can u explain how to do this step by step starting from new->android project..?plz I m new to this platform and want to learn more abt it.....I wiil be thankful to u...!

    ReplyDelete
  4. Hi,

    There is no concept of minimizing an application/activity in android, as this is a mobile. and minimize is a PC concept. All you can do it start a service from a controller activity like I have shown in part 8 of my tutorials available at http://saigeethamn.blogspot.com/2009/09/android-developer-tutorial-for_22.html.
    The service can keep running in the background showing a notification on the status bar. The minimize or hide happens as soon the user presses the back button or another activity.
    Does this serve your purpose?
    For how to create a android project in eclipse, in general, I can put up a step-by-step tutorial very soon.

    ReplyDelete
  5. hey Hi Geetha,

    Having problems with the SimpleNotification says its an error. doesnt recognize it, could you please help me out?

    ReplyDelete
  6. oh plz ignore my previous comment. i found the problem :P, silly me :)

    ReplyDelete
    Replies
    1. hi i want to know how to set the alarm that repeat every day on a specific time in android.
      any help will be appericate

      Delete
    2. If you want it in android versions above 2.3 you can use AlaramClock class,or else for older versions you can use AlaramManager. There are lots of examples for both try searching in google for them.

      Delete
  7. can we delete the notification? such as missed call notification, sms notification.

    ReplyDelete
  8. Hey, me too found problems with the SimpleNotification says its an error. doesnt recognize it !!??

    ReplyDelete
  9. Hi Maiida,

    What is the problem you are facing? Can you please detail?

    Looks like Ayitab also faced something like you but sorted it out by himself. Please let me know what is the problem. I will see if I can help
    -Sai

    ReplyDelete
  10. hai i am kishore , i want to know is there any method or api to attend or reject incoming call in android my email id is kishorebng@yahoo.com

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. Hi,
    Is there a way to list current notifications being displayed?

    Thanks!

    ReplyDelete
  13. just wanted to say thanks for the excellent blog. Well written without any fluff, you rock!

    ReplyDelete
  14. Hi nice tutorial but i have one question. Is there a way to set a notification for a time in the future? e.g. tomorrow at 10am.

    ReplyDelete
  15. Hi Sam,

    I do not see a way of setting a notification for a future time based on some time expression to convey tomorrow or any other future date.
    This may have to be done with some other part of the API, I suppose, using alrams.

    ReplyDelete
  16. does anyone knows the maximum notification it can show?

    ReplyDelete
  17. Hi!

    I was wondering if it is possible to implement a push notification app that communicates with a web server. In the Iphone there's push notifications. Does Android have something similar?
    If so, could you maybe use that as a small tutorial?

    Thanks a lot for all the useful information

    ReplyDelete
  18. Hi Geetha,

    I read about Updating Notification from Android

    Updating the notification

    You can update the information in your status bar notification as events continue to occur in your application. For example, when a new SMS text message arrives before previous messages have been read, the Messaging application updates the existing notification to display the total number of new messages received. This practice of updating an existing Notification is much better than adding new Notifications to the NotificationManager because it avoids clutter in the Notifications window.

    I want only once icon to display along with number of times the notification has occurred. How this can be achieved.

    ReplyDelete
  19. More tutorials on notification bar can be found at:

    http://www.firstdroid.com/2010/05/09/learn-by-example-using-notification-bar/

    Enjoy,
    Azelez

    ReplyDelete
  20. hi geetha
    I'm writing a reminder function for my app. I use repeat alarm, when the alarm goes off at specific time, the onReceive method in BroadcastReceive class will display a status bar notification. But I don't know how to cancel this repeat alarm when user selects the notification or clears it. Cause they are in 2 different classes, i am not sure how to check whether the notification been noticed by the user in my main activity so that I can cancel the alarm. Thanks.

    ReplyDelete
  21. Hi,

    Thisis for whoever asked about how to cancel the notification after the user has seen it:

    You do not have to do anything in the main activity that is in the foreground when the notification was viewed. When you create the Notification object itself, set its flat to FLA_AUTO_CANCEL. Then, the moment the user clicks the Notification and views it, it automatically gets cancelled.

    Fir e.g. in my code, I would have to modifiy this way:

    notifyDetails.flags = Notification.FLAG_AUTO_CANCEL;

    before notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);

    Hope this helps.

    ReplyDelete
  22. Hi,
    I am a novice to Android programming and hoping you might be able to help me out.
    My Activity A uses the Dialer app to make a call. Once the call ends, it shows me call log. Is there any way to get back to my activity A ?

    Thanks and Regards

    ReplyDelete
  23. Hi Sai geetha,
    Thanks for a Grt tutorial. I have one Q?. how to create a notification without button.
    I have created notification for an activity without button. but, if I select the notification from notification bar it is creating multipe intents of that activity.

    ReplyDelete
  24. android:launchMode="singleTop"

    is to be added in the mainifest file.xml to solve the above problem

    ReplyDelete
  25. Hi Sai,
    Very good Explaination,Helped me a Lot,I have a Problem.
    How to Change the Notification.Number Dynamically..Let say i receive 2
    emails my Notification.Number in Status Bar is 2,Note i wont use
    notification Tray to open my email app, rather i will directly go to Email in Menu
    and open it then i read one mail and other is Unread.i Want to Make the
    Notification.Number to 1.I want to Change setLatestEventInfo as well How will i do it???plz help
    Thanks
    Bharath

    ReplyDelete
  26. I am trying to start activity B when clicking on the notification generated by activity A without success. Nothing happens when I click on the notification. Your example in this post opens the browser. Can you please give an example on starting another app (such as another .class in the same apk or another app on the phone)? Thanks!

    ReplyDelete
  27. Hi Sai,
    I need to know y u r using getApplicationcontext()...can we define the className.this

    ReplyDelete
  28. Hi Sai,

    I used this sample code. I got notification icon. but i didnt see the browser . what was the problem and what mistake i have done..

    Thanks in advance

    ReplyDelete
  29. How do I do NOTHING but close the notification bar (and not cancel the notification) in case I do not want to do anything when the notification is clicked ? Passing the intent as null is not working.. I basically do not want to associate anything on clicking the notification ..

    ReplyDelete
  30. Hi mam
    How can I create multiple notification of an activity.All contains is same.I want to show content and system current time.so current time will different.so All bar will be different.How is this is possible??

    ReplyDelete
  31. It's all together: simple, clear, bright, easy to understand... The perfect place for learning Android.
    Thank a lot!

    ReplyDelete
  32. chek this out which will help to learn some good concepts in android

    it is really very nice blog sai geeta copied all from this original blog

    http://androidtutorials60.blogspot.com/2011/04/sqlite-db-example-android-developer.html

    ReplyDelete
    Replies
    1. Anonymous
      you are a bustard.
      Geeta's tutorial is awesome.
      Sai Geeta is real you copied from her.
      that site pageviews only 2066 and
      Sai Geeta's 642,896 so what you say ?
      get out of here.

      Delete
  33. Hi

    How to display notification based on the time from the database even when the app is not running. Its urgent pls help

    ReplyDelete
  34. This comment has been removed by the author.

    ReplyDelete
  35. @Thangadurai,

    1) Goto your home screen, click 'notifications'. You should see the notification there. Click on the notification and it will open the browser.
    OR
    2) From with the app, hold and drag the notification icon downwards. That should list all the current notifications.

    ReplyDelete
  36. hii
    I am suresh, new to android ,i am trying to do ,a project,ie,i want to delete the last dialled call automatically wen we press the end call keyy,
    pls help meeeeeeeee

    ReplyDelete
  37. Mam,how UI framework in android differs from one version to other version

    ReplyDelete
  38. Hi. I am new to android. I want to learn about the background services in android. Can you provide me some easy to learn tutorials for that purpose...???

    ReplyDelete
  39. Hi geetha...
    Thnaks for the infromation given by u guys..but i am having some small querry...that i want to send the message from server side and it should get into my emulator as a notification.so will u please tell this briefly?????

    ReplyDelete
  40. Hi geetha,
    I have a qn reg notification.I want to create a toggle notification.If i click the icon it has to toggle b/n On and Off.Is it possible?

    ReplyDelete
  41. Hello friends,
    thanks for sharing your knowledge.
    I want to get more then event for notification panel.

    I added an button in custom notification panel layout, but i not able to get notification for this added button,means here I want two different one for panel and another one for added button.

    pls suggest me how can i do this.

    ReplyDelete
  42. Hi Sai,

    I loaded your application, When I click on Send Notification, it notifies with a message saying New Alert Click Me!! When I click on it nothing happens.

    ReplyDelete
  43. Is there a way to display notification on the notification bar without making the existing info(time, battery strength ,signal strength etc)on the notification bar disappear ??

    Note : Whenever a notification is triggered the info on the notification bar disappears and then reappears again after few seconds. Is there a way to prevent that ??

    Please mail me the solution @ : keshav.gaur90@gmail.com

    ReplyDelete
  44. hello i want to use slider in my application Can you please give me some information about it?

    ReplyDelete
  45. Hi Sai

    I´m new to android developing, this tutorial is just what i was looking for. Thank you for sharing your ideas. Your blog is very helpful and the code explanation is easy to understand.

    Regards,
    Iazalde Martins..

    ReplyDelete
  46. hello mam ...
    i want help in how to keep record of time of currrent ongoing and other detail of call in an application

    ReplyDelete
  47. Hello ,
    I am facing a problem in handling spinner in android. I am having a problem of initially selected value of spinner.

    So how can i solve it if the user wants to select the value, (not the default value).

    I hope response ASAP.
    Thanks..........

    ReplyDelete
  48. Thanks a lot...Will u tell me how to minimize the android app when a button is pressed?

    ReplyDelete
  49. hi geeta is this possible send notification of the application even when the application is closed or it is running in background??
    please suggest ,me the way..

    ReplyDelete
  50. Hi Sai Geetha,

    i want to create a custom notification with 1 button on it. i want to start an activity when i click on that button.

    basically i want an onButtonClick listener for that notification...

    ReplyDelete
  51. Hi mam, how to create fullscreen as well as transparent activity simultaneously in android,,when i open my transparent activity it goes to background and now i also want to remove status bar on top but it doesnot hapen. plz help

    ReplyDelete
  52. অসাধারন একটা Tutorial. Wonderful. Thanks from the core of my heart for such a nice tutorial.

    Bikash,CSE,2k7,KUET,Bangladesh

    ReplyDelete
  53. hi geetha ...


    i want notifiactions in alarm activity....i.e. when i set the alarm for 2 minutes and exits the application it should notify me or is there any other way so that i can show dialog when alarm times complete.plz help me!!!

    ReplyDelete
  54. hi Geetha,

    I want to implement Home Button Functionality when i clicked on my App whith out using the Home Button.Is it Possible?if it is pls explain

    ReplyDelete
  55. Mam u r awesome and great.

    ReplyDelete
  56. Hi Mam,
    I want to implement remote view in notification and in remote view again I want to add view to create multipule notification at same time with single icon and single sound.

    So please tell me howz possible.

    ReplyDelete
  57. Hi Sai,

    Your application doesnt seem to run well when deployed on the emulator. I get the first activity with both buttons. When I click on 'Send Notification' I get a notification message on status bar but when I click on it nothing happens! Momentarily some drop-down menu seems to open and then retrieves back immediately.

    ReplyDelete
  58. Hello Sai,

    I want to implement white box test cases for clocks,alaram and other submodules of Apps for Android phones which can test the basic sanity test cases for phone via code. Can you suggest me how can I do this.

    ReplyDelete
  59. Mam, in this after cancelling the notification and again clicking send notification it doesn't update the notification time while the activity is onresume state but,

    after onpause and then onresume it works fine

    ReplyDelete
  60. Hi Sai,
    I had a question I am trying your examples and getting to know android?Is it really necessary to know java before you start android development or can we learn both together.I worked on PHP projects before? Please let me know and also I love your tutorials.

    ReplyDelete
  61. your blog is very nice for beginners.

    I had some problem,

    1.i want to store date and time in database.
    2.fetch the date and time from the data base and show notification based on the every date and time.

    1.step is done but how can i do next one please help me..

    Thanks Advance

    ReplyDelete
  62. Hi Sai Geetha,

    I am going through these Android tutorials, they are really simple and very much user understandable. At this point I have a query. Can I know what is a Pending Intent, when & where we can use this Pending Intent.

    Thanks & Regards,
    Sarvesh

    ReplyDelete
  63. I was bit confused on how to invoke notification calls from an activity. Now it got clarified.. Still thinking how to include controls over it in order to control something running in another activity.. Get me an idea if you have.. :)

    ReplyDelete
  64. I want to fire multiple notifications from my application. Tried for a long time but couldn't get it. Can you please provide me a sample code snippet.??

    ReplyDelete
  65. More tutorials on Notification can be found at: http://android.programmerguru.com/android-notifications-example/

    ReplyDelete
  66. after creating notification.in home screen also it shows same notification.but mow i click notification in home screen.it must go to some activity.how i can call the activity

    ReplyDelete
  67. I have problem with the due time set for the notification to come up.
    when I give the code as

    new Notification(R.drawable.android,"New Alert, Click Me!",System.currentTimeMillis() + 50000L);

    It notifies me the second I register the notification. Am I missing something here?

    ReplyDelete
  68. thank you so much especially that all download links works fine ! :)

    ReplyDelete
  69. Hi Geetha,

    All your post are very useful to me. I have a problem in creating a notification view. what i wanted to know is can i create a custom notification with using RemoteView?

    ReplyDelete
  70. Thanx for providing such a helpful information about android notification...i will always like to check notification on my Android Tablet..

    ReplyDelete
  71. Nice information !! but now its time to upgrade.

    ReplyDelete
  72. Android here is how i flashed this rom: 1st i Download apk reverted back to official 2.1 rom, 2nd Apllication iphone flashed to cm 7 stable.3rd updated to Apk Android MyGingerB Gaia 1.3,then lastly,updated this Gaia 2. It took so long to reboot at first,but after a couple of charging,the booting takes forever!hope this issue will be fixed Apk Androidin the next release.

    ReplyDelete
  73. We have seen Activities and Intents. Now we need to move on to services. However, since services mostly interact with a user through notifications, I felt the need to introduce a simple program to deal with Notifications.
    visit here

    ReplyDelete
  74. Hi geetha
    can u please provide me code for Push Notification..
    my email id :madhavglbitm@gmail.com

    ReplyDelete
  75. Hi there. I have a music player actvity playing in the background. How do get that to the front of the screen through the ongoing notification? Any ideas plzz?

    ReplyDelete
  76. Nice post with so helpful details. I really appreciate it. Thanks for sharing,.

    emergency notification

    ReplyDelete
  77. you need to explain in details,you have jst small code

    ReplyDelete