Android Notification Notificationmanager Use Example

Source: Internet
Author: User

Time is too fast, it is difficult to spare some time to do something, there are always all kinds of things. Before actually read the book thanks to the notification of the demo, but the feeling is not enough. This opens the SDK documentation and Google's official status Bar Notifications Developer Guide. In fact, has been reading and online tutorial learning Android, but later found that only the official documents are authentic, although it is English, but more comprehensive, often think of the problem of its solution to look at the official documents to understand. So the next step is to follow the official developer guide. You can learn English, but also learn technology.

The importance of notifications not much to say, now every day the most commonly used to enter the program entrance is informed, so the management of the notification must be familiar. The main three class Notifications,notificationmanager (Notificationcompat.builder for compatibility, Notificationmanager.builde () Joined after 4.1), Pendingintent.

When a new notification arrives, it will be on the status bar at the top of the device, which is a small icon, and the notification will expand when we expand the system's status bar. A brief description of the official drawing:

  

  

The numbers in the illustrations are interpreted as follows:
1. Title of the message
2. Large Icons
3. Overview of the Content
4. Information about the content, such as the number of new messages
5. Small Icons
6. Time of notification arrival

  The three elements that must be required to create a notification: 1. Small icons, 2. The title of the message, 3. Content of the message

Because the level of my emulator API is 14, for compatibility, Notificationcompat.builder is used here to create a notification. Notification of the message since it is the entrance to the program, it is necessary to provide the ability to enter the program by clicking the message, so the use of pendingintent.

  Common methods of the Notificationcompat.builder class:

Public Notification Build (): Constructs a Notification object from the build method.

Public Notificationcompat.builder Setcontenttitle (charsequence title): Sets the title of the message

Public Notificationcompat.builder Setcontenttext (charsequence text): Sets the contents of the message

Public notificationcompat.builder setprogress (int max, int progress, Boolean indeterminate): Sets the progress of the progress bar

Public Notificationcompat.builder setvibrate (long[] pattern): Sets the phone vibrate.

Public Notificationcompat.builder setcontent (remoteviews views): A view that allows users to customize notifications

The general process of the program is as follows: First, a constructor object is obtained by Notificationcompat.builder, then the parameters of the notification are set by means of the method, and finally the build method is used to form a notification object, and then through the notification Manager to display the notification on the status bar. The notification Manager is a system-provided service, so you need to get an instance of the manager through (Notificationmanager) Getsystemservice (Notification_service). These events are started here by buttons to create a new message, update the message, and clear the message.

  

3 Importandroid.app.Activity;4 ImportAndroid.app.NotificationManager;5 Importandroid.app.PendingIntent;6 Importandroid.content.Intent;7 Importandroid.graphics.BitmapFactory;8 ImportAndroid.os.Bundle;9 ImportAndroid.support.v4.app.NotificationCompat;Ten ImportAndroid.view.Menu; One ImportAndroid.view.View; A ImportAndroid.widget.Button; - ImportAndroid.widget.Toast; -  the  Public classMainactivityextendsActivity { - intNotificationid=1; - notificationmanager nm; - pendingintent pendingintent; + Notificationcompat.builder Mbuilder; - //Bitmap Bt_icon = Bitmapfactory.decoderesource (MainActivity.this.getResources (), r.drawable.ic_launcher); + @Override A protected voidonCreate (Bundle savedinstancestate) { at Super. OnCreate (savedinstancestate); - Setcontentview (R.layout.activity_main);
-Mbuilder =NewNotificationcompat.builder (Getbasecontext ()); -NM =(Notificationmanager) - Getsystemservice (notification_service); -Button button1 =(Button) Findviewbyid (R.id.display_button); inButton button2 =(Button) Findviewbyid (R.id.update_button); -Button Button3 =(Button) Findviewbyid (R.id.clear_button); toButton1.setonclicklistener (NewView.onclicklistener () { + - @Override the Public voidOnClick (View v) { * //TODO auto-generated Method Stub $ displaynotification ();Panax Notoginseng } - }); theButton2.setonclicklistener (NewView.onclicklistener () { + A @Override the Public voidOnClick (View v) { + //TODO auto-generated Method Stub - if(Mbuilder! =NULL){ $Mbuilder.setcontenttext ("Changing tiome to 5pm"); $ nm.notify (Notificationid,mbuilder.build ()); - - } the Else - {WuyiToast.maketext (Getbasecontext (), "There is no Notification", Toast.length_short). Show (); the } - } Wu }); -Button3.setonclicklistener (NewView.onclicklistener () { About $ @Override - Public voidOnClick (View v) { - //TODO auto-generated Method Stub - Nm.cancelall (); A } + }); the } - $ @Override the Public BooleanOncreateoptionsmenu (Menu menu) { the //inflate the menu; This adds items to the action bar if it is present. the getmenuinflater (). Inflate (R.menu.main, menu); the return true; - } in Public voiddisplaynotification () the { theIntent i =NewIntent ( This, Notificationview.class); AboutI.putextra ("Notificationid", Notificationid); the thePendingintent pendingintent = thePendingintent.getactivity ( This, 0, I, 0); + //Set various parameters - theMbuilder.setcontenttitle ("New Mail from Mali")Bayi. Setcontenttext ("metting with Customer at 3pm") the . Setsmallicon (R.drawable.ic_launcher) the. Setlargeicon (Bitmapfactory.decoderesource (mainactivity. This. Getresources (), r.drawable.a)); - nm.notify (Notificationid,mbuilder.build ()); - the the } the the}

In order to clearly distinguish between large icons and small icons, here are two different pictures. After running the program, click the first button to generate a notification and pull down the notification bar.

  

For the notification of the message we can not every time a message to generate a notification, so the notification bar has been piling down is neither good-looking nor practical, especially the same kind of news, such as someone to send you a new QQ message. Just update on the message you just made. So it is best to assign an ID to each message so that it can be updated later by ID. Here I click on the second button to refresh the contents of the message.

The message content has changed:

  

The third button is the purge message, which is used by the ClearAll method. Clears all notifications.

Next is the intention, pending meaning is waiting, through the pending intent message is ready to enter another activity's entrance. So we construct another class Notificationview.java to test the entry of the message.

  

Package Com.example.notifications;import Android.app.activity;import Android.app.notificationmanager;import Android.os.bundle;public class Notificationview extends Activity {@Overrideprotected void OnCreate (Bundle Savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview ( r.layout.notification);//Lookup Notification Management Service Notificationmanager NM = (Notificationmanager) getsystemservice (NOTIFICATION_ SERVICE); Nm.cancel (Getintent (). Getextras (). GetInt ("Notificationid"));}}

The code is relatively simple, mainly to help understand the meaning of pending intent. Here we use another cancel method, whose parameter is the ID of the notification passed in, and this method clears the specified notification.

There is also a very common notice is the download time to prompt us to download the progress of the notification, the constructor also provides a setprogress method to facilitate the management of the progress bar. Comment out the code for the Setup parameter in the Displaynotification () method above, and add the following code:

  

1 NewThread (NewRunnable () {2             3 @Override4              Public voidrun () {5                 //TODO auto-generated Method Stub6                 intincr;7                  for(incr=0;incr<=100;incr+=5){8Mbuilder.setprogress (INCR,false);9Nm.notify (0, Mbuilder.build ());Ten                     Try { One                         //Sleep for 5 seconds AThread.Sleep (5*1000); -}Catch(interruptedexception e) { -LOG.D ("Sleep", "Sleep Failure"); the                     } -                 } -Mbuilder.setcontenttext ("Download Complete") -                     //removes the progress bar +. setprogress (0,0,false); - nm.notify (Notificationid, Mbuilder.build ()); +             } A}). Start ();

Note that if you want to display the progress bar, the position of the small icon will be squeezed out, if you set a small icon, do not set a large icon, the small icon will automatically move to the location of the large icon. Effects such as:

  

Android Notification Notificationmanager Use Example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.