Android Notification notification detailed

Source: Internet
Author: User

      • General steps for the use of notification
      • Notification Introduction
      • Pendingintent Introduction
      • customizing notification with Remoteviews
      • Update and remove notifications
      • Set prompt response
      • Appendix

Notification the use of the general steps:

1. Get Status Notification bar management
2. Instantiate the Notification Bar Builder
3. Set Notificationcompat.builder
4. Set Pendingintent
5. Display

Because of the rapid development of Android, and the rapid upgrade of Android version has led to some compatibility issues. For notification, Android3.0 is a watershed, before it was built notification recommended to use Notificationcompate.builder, is an Android down version of the Compatibility Pack, and after Android3.0, it is generally recommended to use NOTIFICATION.B Uilder build. This blog is mainly about the development of android4.x, so here to use Notification.builder to explain the demonstration.

Although the settings for various properties are provided in the notification, a notification object has several properties that must be set, the other properties are optional, and the properties that must be set are as follows:
1), small icons, set using the Setsamllicon () method.
2), title, set using the Setcontenttitle () method.
3), text content, set using the Setcontenttext () method.

Notification Introduction

Notification has two visual styles, a standard view, and a large view. Standard views are common in Android versions, but only android4.1+ versions are supported for large views.
Notification.flags attribute Parameters: (whether multiple can be set):
From the official documentation, a standard view displays a size that is 64DP high. As shown in the following:

1. Notice title
2, Large icon
3. Notification Content
4. Notification message
5. Small Icons
6, the notification time, generally the system time, you can also use the Setwhen () settings.

For large view, its detail area can only display 256DP height of the content, and only for android4.1+ after the device is supported, it is different than the standard view, all need to use the SetStyle () method setting, its approximate effect is as follows:

Android provides us with three implementation classes for displaying different scenarios. respectively:
Notification.bigpicturestyle, displays a 256dp height bitmap in the detail section.
Notification.bigtextstyle, displays a large block of text in the detail section.
Notification.inboxstyle, displaying a line of text in the detail section

Notification.flag_show_lights//Tri-color lamp reminder, you must add the marker when using a tri-color lamp reminder
Notification.flag_ongoing_event//initiating a running event (active)
Notification.flag_insistent//Let sound, vibration infinite loop until the user responds (cancel or open)
Notification.flag_only_alert_once//After initiating Notification, ringtones and vibrations are performed only once
Notification.flag_auto_cancel//user automatically disappears after clicking notifications
Notification.flag_no_clear//Only when all clear, the Notification will clear, not clear the notice (QQ notice can not be cleared, is the use of this.) There are also Baidu notification bar inside the search box is also this).
How to use: After setting the properties, set the
Notification Notification = Builder.build ();
Notification.flags = notification.flag_only_alert_once;

Pendingintent Introduction

For a notification, it displays a limited number of messages and is generally used only to prompt some summary information. But the general short message, does not express the need to tell the user the entire content, therefore needs to bind an intention, when the user clicks the notification, invokes an intention to display the activity to display the detailed content. In notification, instead of using regular intent to pass an intent, use pendingintent.
First of all, the difference between intent and pendingintent, Pendingintent can be seen as the packaging of intent, by name can be seen Pendingintent used to deal with the impending intention, and intent used to deal with the immediate occurrence of the intention. For notifications, it is a system-level global notification and does not determine when the intent is being executed. When executing pendingintent outside the application, because it holds the context of the triggering application, the external application can execute the intent in the pendingintent as in the current application, even if the application that responds to the notification is destroyed when executed. It can also be performed as usual in the context of the presence of pendingintent, and can also handle the additional information that intent says it brings.
Pendinginteng.getbroadcast (Contex, Requestcode, intent, flags)
Pendinginteng.getservice (Contex, Requestcode, intent, flags)
Pendinginteng.getactivity (Contex, Requestcode, intent, flags)
Pendinginteng.getactivities (Contex, Requestcode, intent, flags)
Where the flags attribute parameter:
Flag_one_shot means that the returned pendingintent can only be executed once and disappear automatically after execution
Flag_no_create indicates that if the description of the pendingintent does not exist, the corresponding pendingintent is not created, but returns null
Flag_cancel_current indicates that the corresponding pendingintent already exists, cancels the former and then creates a new pendingintent
Flag_update_current represents the updated pendingintent, and if the built pendingintent already exists, replace it, often.

customizing notification with Remoteviews

You need to use remoteviews.remoteviews to describe the structure of a view hierarchy that can be displayed in another process. Remoteviews provides multiple constructors, typically using Remoteviews (String packagename,int layoutid). The first parameter is the name of the package, and the second is the ID of the layout resource. When you get to the Remoteviews object, you can use its series of setxxx () methods to set the control's properties through the control's ID. Finally, use the NotificationCompat.Builder.setContent (Remoteviews) method to set it to a notification.
Remoteviews.setonclickpendingintent (ViewId, pendingintent), can enter different activity. Such as:
Remoteviews.setonclickpendingintent (R.id.titletv, pendingintent.getactivity (context, 0,
New Intent (context, Scrollingactivity.class), pendingintent.flag_update_current);

Update and remove notifications

When you use Notificationmanager.notify () to send notifications, you need to pass an identifier that uniquely identifies the notification. For some scenarios, not unlimited add new notifications, sometimes need to update the information of the original notification, this time can be rewritten to build notification, and use the same identifier with the previous notification to send notifications, this time the old notification is replaced by the new notification, the effect of the update notification.
How do I cancel a notification when it is displayed after the status bar but after use? Android provides us with two ways to remove notifications, one is to notification own maintenance, to use the Setautocancel () method to set whether to maintain, to pass a Boolean type of data. Another way to maintain the Notificationmanager Notification Manager object is to use cancel (int) to remove a specified notification when it sends a notification through notify (), specifying the notification ID to operate the notification. You can also use Cancelall () to remove all notifications.
Use Notificationmanager to remove the specified notification example:

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);mNotificationManager.cancel(0);
Set prompt response

For some notifications, you need to call some of the resources of the device, so that users can quickly discover that there are new notifications, generally settable responses are: ringtones, flash, vibration. For these three properties, Notificationcompat.builder provides three method settings:
Setsound (Uri Sound): sets a ringtone to respond to when notified. Pass a URI parameter in the form "File:///mnt/sdcard/Xxx.mp3".
setlights (int argb, int onms, int offms): Sets the blinking rate of the front LED lights, the number of milliseconds, and the number of milliseconds to pause.
Setvibrate (long[] pattern): Sets the mode of vibration, with a long array to hold the vibration of the millisecond interval.
Most of the time, we do not need to set a specific response effect, just to follow the user device on the system notification effect, then you can use the SetDefaults (int) method to set the default response parameters, in notification, its parameters using constants defined, We just need to use:
Default_all: Ringtones, flashes, vibrations are system default.
Default_sound: System default ringtone.
Default_vibrate: System default vibration.
Default_lights: System default Flash.
Set the vibration, need permission: Android.permission.VIBRATE
Setting the Flash requires permission: Android.permission.FLASHLIGHT

Appendix

Here is a notification tool class that I encapsulated:

 Packagecom.test.testandroid;ImportAndroid.app.Notification;ImportAndroid.app.NotificationManager;ImportAndroid.app.PendingIntent;ImportAndroid.content.Context;ImportAndroid.content.Intent;ImportAndroid.graphics.BitmapFactory;ImportAndroid.widget.RemoteViews;/** * Created by Administrator on 2016-6-19. * Notification Builder Android */ Public  class notificationutil {    PrivateContext context;PrivateNotificationmanager Notificationmanager; Public Notificationutil(Context context) { This. Context = Context;    Notificationmanager = (Notificationmanager) context.getsystemservice (Context.notification_service); }/** * Normal notification * *     Public void postnotification() {Notification.builder Builder =NewNotification.builder (context); Intent Intent =NewIntent (context, mainactivity.class);//need to jump to the specified pagePendingintent pendingintent = pendingintent.getactivity (Context,0, intent, pendingintent.flag_update_current);        Builder.setcontentintent (pendingintent); Builder.setsmallicon (R.mipmap.ic_launcher);//Settings iconBuilder.setcontenttitle ("title");//Set the title of the notificationBuilder.setcontenttext ("Content");//Set the content of the notificationBuilder.setwhen (System.currenttimemillis ());//Set the time for notifications to arriveBuilder.setautocancel (true);//The disappearance of their own maintenance notificationsBuilder.setticker ("New Message");//When the first hint disappears, it appears on the notification bar.Builder.setongoing (true); Builder.setnumber ( -);        Notification Notification = Builder.build (); Notification.flags = Notification.flag_no_clear;//Notification will only clear when all is clearedNotificationmanager.notify (0, notification); }/** * Use the downloaded Notification, after 4.0 to use the <p></p> * Notification.builder class provides a setprogress (int max,int prog     Ress,boolean indeterminate) method is used to set the progress bar, * Max is used to set the maximum number of progress, progress is used to set the current progress, indeterminate is used to set whether it is a progress bar to determine the progress.     * With the indeterminate setting, two different styles of progress bars can be implemented, one is a progress tick (true), and the other is circular flow (false). */     Public void postdownloadnotification() {FinalNotification.builder Builder =NewNotification.builder (context); Builder.setsmallicon (R.mipmap.ic_launcher). Setticker ("Showprogressbar"). Setcontentinfo ("ContentInfo"). Setongoing (true). Setcontenttitle ("Contenttitle"). Setcontenttext ("ContentText");//Simulation Download Process        NewThread (NewRunnable () {@Override             Public void Run() {intprogress; for(Progress =0; Progress < -; Progress + =5) {//Set the third parameter of Setprogress to True to show a progress bar style with no definite progressBuilder.setprogress ( -, Progress,false); Notificationmanager.notify (0, Builder.build ());Try{Thread.Sleep (1* +); }Catch(Interruptedexception e) {System.out.println ("Sleep Failure"); }} builder.setcontenttitle ("Download Complete"). Setprogress (0,0,false). Setongoing (false); Notificationmanager.notify (0, Builder.build ());    }}). Start (); }/** * Large view notification cannot be used after 4.1,bigtextstyle<p></p> * ****************************************************&L     T;p></p> * Helper class for generating Large-format notifications this include a lot of text. * Here's how do you ' d set the <code>BigTextStyle</code> on a notification: * <pre class= "Prettyprint "> * Notification notif = new Notification.builder (mcontext) *. setcontenttitle (&quot; New Mail from &quot; + sender.tostring ()) *. setcontenttext (subject) *. Setsmallicon (r.drawable.new_mail) *. setlargeic On (ABITMAP) *. SetStyle (New Notification.bigtextstyle () *. BigText (averylongstring)) *. Build (     ); * </pre> * * @see notification#bigcontentview * *     Public void postbigtextnotification() {Notification.bigtextstyle TextStyle =NewNotification.bigtextstyle (); Textstyle.setbigcontenttitle ("Big headline")//Title. Setsummarytext ("Summarytext"). BigText ("Helper class for generating Large-format notifications"+"that include a lot of text; !!!!!!!!!!!"+"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"); Notification.builder Builder2 =NewNotification.builder (context); Builder2.setsmallicon (R.mipmap.ic_launcher);//Small Icons        //Large IconsBuilder2.setlargeicon (Bitmapfactory.decoderesource (Context.getresources (), r.mipmap.ic_launcher));//r.mipmap.closeBuilder2.setticker ("Showbigview_text"). Setcontentinfo ("ContentInfo");        Builder2.setstyle (TextStyle); Builder2.setautocancel (true); Notificationmanager.notify (0, Builder2.build ()); }/** * Large layout notification can be used after 4.1, large layout picture * /     Public void postbigpicturenotification() {Notification.bigpicturestyle Bigpicturestyle =NewNotification.bigpicturestyle (); Bigpicturestyle.bigpicture (Bitmapfactory.decoderesource (Context.getresources (), r.mipmap.ic_launcher));//r.drawable.backNotification.builder Builder =NewNotification.builder (context); Builder.setsmallicon (R.mipmap.ic_launcher);//Small Icons        //Large IconsBuilder.setlargeicon (Bitmapfactory.decoderesource (Context.getresources (), r.drawable.ic_stop)); Builder.setticker ("Showbigview_picture"). Setcontentinfo ("ContentInfo");        Builder.setstyle (Bigpicturestyle); Builder.setautocancel (true); Notificationmanager.notify (0, Builder.build ()); }/** * Large layout notification can be used after 4.1, Inboxstyle */     Public void postinboxnotification() {Notification.inboxstyle Inboxstyle =NewNotification.inboxstyle (); Inboxstyle.setbigcontenttitle ("Inboxstyle"); Inboxstyle.setsummarytext ("Test"); for(inti =0; I <Ten; i++) {Inboxstyle.addline ("NEW:"+ i); } Notification.builder Builder5 =NewNotification.builder (context); Builder5.setsmallicon (R.mipmap.ic_launcher);//Small Icons        //Large IconsBuilder5.setlargeicon (Bitmapfactory.decoderesource (Context.getresources (), r.drawable.ic_stop)); Builder5.setticker ("Showbigview_inboxstyle"). Setcontentinfo ("ContentInfo");        Builder5.setstyle (Inboxstyle); Builder5.setautocancel (true); Notificationmanager.notify (0, Builder5.build ()); }/** * Custom Notification <p></p> * Do not set notification.contentintent = Pendingintent; The following exception is reported: * Android.app . Remoteserviceexception: * Bad notification posted from the package com.test.testandroid:Couldn ' t expand remoteviews for: Statusbarnotification (* pkg=com.test.testandroid user=userhandle{0} id=0 tag=null score=0 key=0|com.test.testandroid |0|null|10168|0:notification * (pri=0 contentview=com.test.testandroid/0x7f040038 vibrate=null sound=null defaults=0 X0 flags=0x10 Color=0xff00aeff vis=private)) * /     Public void postcustomnotification() {Remoteviews contentviews =NewRemoteviews (Context.getpackagename (), r.layout.mynotification);        Contentviews.setimageviewresource (R.id.imagenotifi,r.mipmap.ic_launcher); Contentviews.settextviewtext (R.id.titletv,"Custom notification title"); Contentviews.settextviewtext (R.id.texttv,"Custom notification content"); Intent Intent =NewIntent (context, mainactivity.class); Pendingintent pendingintent = pendingintent.getactivity (Context,0, intent, pendingintent.flag_update_current);        Contentviews.setonclickpendingintent (R.id.titletv, pendingintent); Contentviews.setonclickpendingintent (R.id.texttv, pendingintent.getactivity (context,0,NewIntent (context, Scrollingactivity.class), pendingintent.flag_update_current); Notification.builder Builder =NewNotification.builder (context);        Builder.setsmallicon (R.mipmap.ic_launcher); Builder.setcontenttitle ("Custom Notification"); Builder.setcontenttext ("Custom Test"); Builder.setticker ("Custom Ticker"); Builder.setautocancel (true);        Builder.setcontent (contentviews); Notificationmanager.notify (0, Builder.build ()); } Public void Cancelbyid() {Notificationmanager.cancel (0);//corresponds to Notificationmanager.notify (id,notification); first parameter} Public void cancelallnotification() {notificationmanager.cancelall (); }}

How to use:

new CustomNotification(this);//        customNotification.postNotification();//        customNotification.postDownloadNotification();//        customNotification.postBigTextNotification();//        customNotification.postBigPictureNotification();        customNotification.postInboxNotification();

Reference:
(1) The notification of android-notice;

Android Notification notification detailed

Related Article

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.