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());
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.
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.
ReplyDeleteGanesh
Ganesh,
ReplyDeleteWhat 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.
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...!
ReplyDeleteHi,
ReplyDeleteThere 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.
hey Hi Geetha,
ReplyDeleteHaving problems with the SimpleNotification says its an error. doesnt recognize it, could you please help me out?
oh plz ignore my previous comment. i found the problem :P, silly me :)
ReplyDeletehi i want to know how to set the alarm that repeat every day on a specific time in android.
Deleteany help will be appericate
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.
Deletecan we delete the notification? such as missed call notification, sms notification.
ReplyDeleteHey, me too found problems with the SimpleNotification says its an error. doesnt recognize it !!??
ReplyDeleteHi Maiida,
ReplyDeleteWhat 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
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
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteHi,
ReplyDeleteIs there a way to list current notifications being displayed?
Thanks!
just wanted to say thanks for the excellent blog. Well written without any fluff, you rock!
ReplyDeleteHi 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.
ReplyDeleteHi Sam,
ReplyDeleteI 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.
does anyone knows the maximum notification it can show?
ReplyDeleteHi!
ReplyDeleteI 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
Hi Geetha,
ReplyDeleteI 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.
More tutorials on notification bar can be found at:
ReplyDeletehttp://www.firstdroid.com/2010/05/09/learn-by-example-using-notification-bar/
Enjoy,
Azelez
hi geetha
ReplyDeleteI'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.
Hi,
ReplyDeleteThisis 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.
Hi,
ReplyDeleteI 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
Hi Sai geetha,
ReplyDeleteThanks 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.
android:launchMode="singleTop"
ReplyDeleteis to be added in the mainifest file.xml to solve the above problem
Hi Sai,
ReplyDeleteVery 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
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!
ReplyDeleteHi Sai,
ReplyDeleteI need to know y u r using getApplicationcontext()...can we define the className.this
Hi Sai,
ReplyDeleteI 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
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 ..
ReplyDeleteHi mam
ReplyDeleteHow 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??
It's all together: simple, clear, bright, easy to understand... The perfect place for learning Android.
ReplyDeleteThank a lot!
chek this out which will help to learn some good concepts in android
ReplyDeleteit 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
Anonymous
Deleteyou 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.
Hi
ReplyDeleteHow to display notification based on the time from the database even when the app is not running. Its urgent pls help
This comment has been removed by the author.
ReplyDelete@Thangadurai,
ReplyDelete1) 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.
hii
ReplyDeleteI 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
Mam,how UI framework in android differs from one version to other version
ReplyDeleteHi. 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...???
ReplyDeleteHi geetha...
ReplyDeleteThnaks 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?????
Hi geetha,
ReplyDeleteI 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?
Hello friends,
ReplyDeletethanks 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.
Hi Sai,
ReplyDeleteI 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.
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 ??
ReplyDeleteNote : 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
hello i want to use slider in my application Can you please give me some information about it?
ReplyDeleteHi Sai
ReplyDeleteI´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..
hello mam ...
ReplyDeletei want help in how to keep record of time of currrent ongoing and other detail of call in an application
Hello ,
ReplyDeleteI 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..........
Thanks a lot...Will u tell me how to minimize the android app when a button is pressed?
ReplyDeletehi geeta is this possible send notification of the application even when the application is closed or it is running in background??
ReplyDeleteplease suggest ,me the way..
Hi Sai Geetha,
ReplyDeletei 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...
how
ReplyDeleteHi 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অসাধারন একটা Tutorial. Wonderful. Thanks from the core of my heart for such a nice tutorial.
ReplyDeleteBikash,CSE,2k7,KUET,Bangladesh
hi geetha ...
ReplyDeletei 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!!!
hi Geetha,
ReplyDeleteI 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
Mam u r awesome and great.
ReplyDeleteHi Mam,
ReplyDeleteI 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.
Hi Sai,
ReplyDeleteYour 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.
Hello Sai,
ReplyDeleteI 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.
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,
ReplyDeleteafter onpause and then onresume it works fine
Hi Sai,
ReplyDeleteI 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.
your blog is very nice for beginners.
ReplyDeleteI 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
Hi Sai Geetha,
ReplyDeleteI 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
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.. :)
ReplyDeleteI 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.??
ReplyDeleteMore tutorials on Notification can be found at: http://android.programmerguru.com/android-notifications-example/
ReplyDeleteafter 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
ReplyDeleteI have problem with the due time set for the notification to come up.
ReplyDeletewhen 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?
thank you so much especially that all download links works fine ! :)
ReplyDeleteThanks for the code..
ReplyDeleteHi Geetha,
ReplyDeleteAll 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?
Thanx for providing such a helpful information about android notification...i will always like to check notification on my Android Tablet..
ReplyDeleteNice information !! but now its time to upgrade.
ReplyDeleteAndroid 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.
ReplyDeleteWe 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.
ReplyDeletevisit here
Hi geetha
ReplyDeletecan u please provide me code for Push Notification..
my email id :madhavglbitm@gmail.com
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?
ReplyDeleteNice post with so helpful details. I really appreciate it. Thanks for sharing,.
ReplyDeleteemergency notification
you need to explain in details,you have jst small code
ReplyDelete