Use of Android Notification

Source: Internet
Author: User

The use of Notification requires importing 3 classes

Import Android.app.pendingintent;import Android.app.notificationmanager;import android.app.Notification;

Code Examples and Descriptions

Notificationmanager nm =(Notificationmanager) Getsystemservice (Context.notification_service); Notification N=NewNotification (R.drawable.chat,"hello,there!", System.currenttimemillis ()); N.flags=Notification.flag_auto_cancel; Intent I=NewIntent (Arg0.getcontext (), Notificationshow.class); I.setflags (Intent.flag_activity_clear_top|intent.flag_activity_new_task); //pendingintentPendingintent contentintent =pendingintent.getactivity (Arg0.getcontext (), R.string. App_name, I, pendingintent.flag_update_current); N.setlatesteventinfo (Arg0.getcontext (),"hello,there!",         "Hello,there,i ' m John.", contentintent); Nm.notify (R.string. app_name, N);

Each piece of code is analyzed in turn:

Otificationmanager nm = (Notificationmanager) getsystemservice (Context.notification_service);

Creates a notificationmanager that creates a NM object responsible for "emitting" and "canceling" Notification.

New " hello,there! " , System.currenttimemillis ());              = Notification.flag_ongoing_event;  

Create Notification, with the parameters: Icon's resource ID, scrolling information displayed on the status bar, time. The N object that is created is used to describe the information that appears in the system notification bar, and we will then see the intent that is set on the N object to click on this notification. ‘

N.flags = Notification.flag_auto_cancel;

Set N.flags to Notification.flag_auto_cancel, which indicates that the notification can be cleared when the user clicks clear.

New Intent (Arg0.getcontext (), Notificationshow.  Class); I.setflags (Intent.flag_activity_clear_top| Intent.flag_activity_new_task);

Create a intent that intent make this intent when the user clicks the notification

Note that if you want to start an ACTIVITY with the Intent, be sure to set the Intent.flag_activity_new_task tag.

Intent.flag_activity_clear_top: If there is activity to start in the current task, turn off all activity before the acitivity, and to avoid creating instances of the activity by placing this activity before

Intent.flag_activity_new_task: The system checks to see if there is a task for the activity that is being started in all the currently created tasks, and if so, creates an activity on that task, If not, a new task with the Activity property is created, and an activity on the new task. See also "(reprint) Android under Affinities and task"

Pendingintent contentintent = pendingintent.getactivity (        arg0.getcontext (),         R. string . App_name,         I,         pendingintent.flag_update_current);

Pendingintent for Intent packaging, here is a description of the start intent, Pendingintent.getactivity returns the Pendingintent said, The intent in this pendingintent instance is the intent used to start the Activity. The parameters of the pendingintent.getactivity are: Context, the sender's request code (can fill 0), for the system to send the intent, flag bit.

Where pendingintent.flag_update_current indicates that if the pendingintent of the description already exists, The extra data for the existing pendingintent is changed to the extra data for the new pendingintent.

Here is a brief talk about the difference between Intent and pendingintent:

Intent: The intention, that is to tell the system what I want to do, and then the system according to this Intent do the corresponding thing. such as startactivity is equivalent to sending a message, while intent is the content of the message.

Pendingintent: Packaging Intent,intent is our intention to use startactivity, StartService, or sendbroadcast to start a work directly. At some point, we can not call startactivity, startservide or sendbroadcast directly, but send intent when a program or system reaches a certain condition. As notification here, when the user clicks Notification, the system issues an activity Intent. So if we don't have a way to tell the system, the system doesn't know whether to use StartActivity, StartService or Sendbroadcast to start intent (and of course other "descriptions"), So here we need pendingintent.

N.setlatesteventinfo (        arg0.getcontext (),        "hello,there! " ,          " Hello,there,i ' m John. " ,         contentintent);

Set the information displayed in the Notification drop-down box, with the following parameters: Context, title, content, Pendingintent.

Nm.notify (r..string. App_name, N);

Start notification with the following parameters: Identify the ID value of the notification in your program (used to distinguish between different notifycation in the same program, if there is only one notification in the program then you can fill anything you want, However the type must be int), the notification to be notified.

How to make your own notification like Android QQ can appear under the "Running" column

Actually very simple, just set notification.flags = Notification.flag_ongoing_event;

How to change the layout of Notification under the "Running" column

Create Remoteviews and assign it to Notification.contentview, and then assign Pendingintent to Notification.contentintent, such as:

 pendingintent contentintent = Pendingintent.getactivity (Arg0.getcontext (), R.
    string  .app_name, I, pendingintent.flag_             Update_current); Remoteviews RV  = new  remoteviews (main. This  .getpackagename (), r.layout.notification_view); Rv.setimageviewresource (R.id.image, R.drawable.chat); Rv.settextviewtext (R.id.text,   hello,there,i ' m John.   "  = rv;n.contentintent  =< Span style= "color: #000000;" > Contentintent; Nm.notify (R.  string . App_name, n); 

Note that if Contentview is used, then do not use Notification.setlatesteventinfo. If the setlatesteventinfo is assigned to the Notification.contentview code, then the Contentview effect will be overwritten, showing the effect of setlatesteventinfo; Setlatesteventinfo before the Notification.contentview code, then the Notification.contentview effect is displayed, That is, regardless of the custom effect you want to setlatesteventinfo or Contentview, make sure there is always only one set of code, because when the last sentence is bound, The previous setup of Contentview or Setlatesteventinfo code is completely unnecessary.

Case Effect:

Notificationmanager Mnotificationmanager =(Notificationmanager) Mycontext.getsystemservice (Notification_service); Longwhen =System.currenttimemillis (); Notification Notification=NewNotification (Resource, Tickertext, when); /** Notification.flag_auto_cancel, which indicates that the notification can be cleared when the user clicks clear*/Notification.flags=notification.flag_ongoing_event; Notification.flags= Notification.flag_no_clear;//permanent, cannot deleteNotification.defaults= Notification.default_sound;//SoundNotification.defaults = notification.default_lights;//LightNotification.defaults = notification.default_vibrate;//Vibration                       /** Create a click event to open Activity Object * * If you want to start an activity with the Intent, be sure to set the Intent.flag_activity_ne W_task Tag * Intent.flag_activity_clear_top: If there is ACTIVITY to start in the current TASK, then all activi before that acitivity Ty is switched off and the activity is set to avoid creating instances of activity*/Intent notificationintent=NewIntent (Mycontext, voiceidentifyactivity.class); Notificationintent.setflags (Intent.flag_activity_clear_top|intent.flag_activity_new_task); /** Click Start activity and startactivity () same meaning * indicates that if the description pendingintent already exists, the extra data of the existing pendingintent is changed              The extra data for the new pendingintent. */pendingintent contentintent= Pendingintent.getactivity (Mycontext,0, Notificationintent, pendingintent.flag_update_current);                         Notification.setlatesteventinfo (Mycontext, Contenttitle, contenttext,contentintent); /** Use Mnotificationmanager Notify method to notify users to generate title bar message Notification*/mnotificationmanager.notify (R.string. app_name, notification);

Notification can be understood as the meaning of the notification is generally used to display broadcast information with notification must be used Notificationmanager

There are three steps to using notification generally, as shown below

① general access to system-level service Notificationmanager.

Call the Context.getsystemservice (Notification_service) method to return to the Notificationmanager instance

② instantiates the notification and sets its properties

Constructs Notification instance with Notification constructor public Notification (int icon, charsequence tickertext, Long)

③ through Notificationmanager, it's OK.

Notificationmanager There are two ways: Notify () send notification cancel (...) Cancel Notification

Here is a code example to introduce notification

Initialize Notificationmanager and notification two member variables first

The layout won't stick. It's two buttons. Look at the Send button

Sendbutton.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {Intent Intent=NewIntent (notificationactivity. This, Notificationactivity.class); Pendingintent pendingintent= Pendingintent.getactivity (notificationactivity. This,0, Intent,0); Notification.setlatesteventinfo (notificationactivity. This,"a piece of your message","information from Zhang San", pendingintent);              Notificationmanager.notify (id,notification); Notificationmanager.notify (ID+1, notification); }  })  

Setlatesteventinfo (...) Inside the parameters of: (see figure II) Notice there are two exactly the same message, yes you did not read wrong, this is because I used Notificationmanager notify (notice) two times and the ID is different, ID is the int type is the identifier of the notification information. Although the above two messages are identical, but because of the different ID, so Android will still display two messages.
What do you mean by the role that parameter pendingintent plays in Setlatesteventinfo? Pendingintent can be executed in another place, not with immediate intent. When the user clicks on the extension notice, pendingintent intention to start execution, example two I click on one of the messages, immediately into another activity ...
As seen above, in addition to the notification set the icon, outside the title can also set the tone, vibration, flash details please see my turn of a piece of article notification use detailed .....

Package com.study.android;  Import android.app.Activity;  Import android.app.Notification;  Import Android.app.NotificationManager;  Import android.app.PendingIntent;  Import Android.content.Context;  Import android.content.Intent;  Import Android.os.Bundle;  Import Android.view.View;  Import Android.view.View.OnClickListener;    Import Android.widget.Button;  Public classMainactivity extends Activity {PrivateButton startbtn; PrivateButton cancelbtn; Private StaticFinalinthello_id =1;      Notificationmanager Mnotificationmanager;      Notification mnotification; /** Called when the activity is first created.*/@Override Public voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);                    Setcontentview (R.layout.main); STARTBTN=(Button) Findviewbyid (R.ID.STARTBTN); CANCELBTN=(Button) Findviewbyid (R.ID.CANCELBTN); //① getting references to NotificationmanagerString NS =Context.notification_service; Mnotificationmanager= (Notificationmanager) This. Getsystemservice (NS); //② Initialize Notification        inticon =R.drawable.ic_launcher; Charsequence Tickertext="Hello"; Longwhen =System.currenttimemillis (); Mnotification=NewNotification (Icon,tickertext,when); Mnotification.defaults=Notification.default_all; Mnotification.flags|=notification.flag_no_clear; Mnotification.flags|=notification.flag_show_lights; //③ defining notification messages and PendingintentContext context = This; Charsequence Contenttitle="My Notification"; Charsequence ContentText="Hello World"; Intent notificationintent=NewIntent ( This, Mainactivity.class); Pendingintent contentintent= pendingintent.getactivity (Context,0, Notificationintent,0 );                    Mnotification.setlatesteventinfo (context, Contenttitle, ContentText, contentintent); //④ the encapsulated notification into the Notificationmanager.//Turn on NotificationsStartbtn.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {mnotificationmanager.notify (hello_id,mnotification);                    }          }); //Cancel NotificationCancelbtn.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {mnotificationmanager.cancel (hello_id);      }          }); }  }  

Use of Android Notification

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.