Android notification fully parse "go"

Source: Internet
Author: User

Transferred from: http://www.itnose.net/detail/6169442.html

Notifications in Android 4.4 and Lower

Notification is a very important part, it is closely related to service,broadcastreceiver,intent and so on, good use of notification can make your app's activity relative to no notification App has been greatly increased.

It is obvious that this article will introduce the notification of 4.4 and below in detail. As for the features of Android 5.0, I plan to write a special feature for the holidays. Download it as a review of knowledge. After all, Wen knows new, haha.

The notification system allows your app to keep the user informed about events, such as new chat messages or a calendar EV Ent. Think of notifications as a news channel that alerts the user to important events as they happen or a log that chronicles Events while the user was not paying attention.

Notification enables your app to inform users of events in the app, such as a new message or a calendar event. It can be thought that notification is a news channel that is used to notify users of important events when they are not aware of them.

Anatomy of a notification

Base Layoutat a minimum, all notifications consist of a base layout, including:the sending application ' s notification icon  Or the sender ' s PHOTOA notification title and Messagea Timestampa secondary icon to identify the sending application when The sender ' s image is     shown for the main icon

Basic layout of notification

At a minimum, all notifications are composed of basic layouts, including:

Sends an image of the icon or sender of the notification application.
The title and message of the notification.
Time stamp
When main icon is used to display sender's image, secondary icon is used to display the icon that sends the application.

Expanded layoutsyou has the option to provide more event detail. You can use this to show the first few lines of a message or show a larger image preview. This provides the user with additional context, and-in some cases-may allow the user-to-read a message in its entirety . The user can pinch-zoom or Two-finger glide in order to toggle between base and expanded layouts. For single event notifications, Android provides-expanded layout templates (text and image) for the re-use in your Application.

Extended layout of notification

You can choose to provide more details about the event. You can use it to display some lines of a message or to display a preview of a picture. These provide additional content to the user and, in some cases, allow the user to read the complete information. The user can open the extended layout by pinch-zoom or swiping with both fingers. Android provides two ways to extend the layout of a single notification (IMAGE,TEXT) for you to use in your application.

Title of 1.notification
2. Send the icon of the notification application or the sender's image.
Message of 3.notification
The number of 4.notification displays
5. When main icon is used to display sender's image, secondary icon is used to display the icon that sends the application.
6. Timestamp, which defaults to the time the system is notified.

Actions

 Android supports optional actions that is displayed at the bottom of the notification. With actions, users can handle the most common tasks for a particular notification from within the notification shade with Out has to open the originating application. This speeds up interaction and, in conjunction with "Swipe-to-dismiss", helps users to streamline their notification triag ing experience. Be judicious with how many actions, include with a notification. The more actions your include, the more cognitive complexity you create. Limit yourself to the fewest number of actions possible by only including the most imminently important and meaningful one S.good candidates for actions on notifications is actions that are:essential, frequent and typical for the content type Y Ou ' re displayingtime-criticalnot overlapping with neighboring actionsavoid actions that are:ambiguous,duplicative of the Default action of the notification (such as "Read" or "Open") 

Android supports the display of optional actions at the point of notification. With these actions, users can handle most of the same tasks without opening the app. This sets the speed of happy interactions, and the combination of sliding disappears allows the user to streamline their notification processing experience.

Make a wise decision about the number of actions placed within your notification. If you include more action, you increase the complexity of the interaction. Please select one or two important and meaningful action.

A good candidate action has the following characteristics:

An action that is important, typical, and frequently used for this notification.
. Time is pressing
Do not overlap with adjacent action

Avoid the following actions:

. Vague and ambiguous
. and click Notification Action repeat (such as "Read" or "Open")

Design guidelines

. Personalization
. Navigate to the right place
The priority of setting notifications correctly

Take a look at the priority settings, other explanations you can refer to the official website.
Use method setpriority (int pri) to specify precedence

The corresponding properties are as follows:

Notification.priority_default (priority is 0)
Notification.priority_high
Notification.priority_low
Notification.priority_max (priority is 2)
Notification.priority_min (priority is-2)

Now, let's take a look at how to implement a notification. It is estimated that the most common practice now is the following:

Notification Notification = new Notification (R.drawable.ic_launcher,  getText (r.string.app_name),            System.currenttimemillis ());    Intent notificationintent = new Intent (this, myservice.class);    Pendingintent pendingintent = pendingintent.getactivity (this, 0,     notificationintent, 0);    Notification.setlatesteventinfo (This, GetText (R.string.hello_world),            GetText (R.string.hello_world), pendingintent);    Startforeground (1, notification);

This is the start of a notification in the service, but you must remember that this method is outdated, that is, Google has not advocated the use of this method to start a notification. The official recommendation is to use the V4 package under Notificationcompat.builder so that we can set various properties.

Well, now let's take a look at the concrete implementation of the notification.

1. Create a simple notification.

Required notification contentsnotification must contain content a notification object must contain the following: A notification must contain the following properties: A small icon, set by Setsmallicon () a small icon, set with Setsmallicon (), corresponding to area 2nd in a title, set by Setcontenttitle () a title, set with Setcontenttitle (), corresponding to the 1th area detail text, set by Setcontenttext () detailed text, with Setcontenttext () To set that corresponds to area 3rd in

These three must be set, as for the other extensions are requirements. The code is as follows:

Private Notificationmanager Manager; Notificationcompat.builder notifybuilder; @Overrideprotected void OnCreate (Bundle savedinstancestate) {    Super.oncreate (savedinstancestate);    Setcontentview (r.layout.activity_main);    /* Instantiate Notificationmanager to get system service *    /manager = (Notificationmanager) getsystemservice (notification_service);} /** * Displays the simplest notification, the three set methods in the following method are required to be set * * @param view */public void simnotification (view view) {    Toast.maketext (this , "HHA", Toast.length_long). Show ();    Notifybuilder = new Notificationcompat.builder (this)/            * Set small icon*/            . Setsmallicon (R.drawable.ic_launcher )            /* Set title*/            . Setcontenttitle ("notifications")/            * Set verbose text *            /. Setcontenttext ("Hello World");    Manager.notify (Notifybuilder.build ());}

The comments in the code are already detailed, and Simnotification is bound to a button. In this way, we have achieved the simplest notification.

2. Create a click to jump to other activity's notification.

 /** * Click Jump to assign Activity * * @param view */public void Largepicture (view view) {/* Instantiate Notificationmanager for system service */MA    Nager = (Notificationmanager) getsystemservice (Notification_service);    Click the intent action is to jump to Intent Intent resultintent = new Intent (this, mainactivity.class);    Resultintent.setflags (Intent.flag_activity_single_top);    Pendingintent pendingintent = pendingintent.getactivity (this, 0, resultintent, pendingintent.flag_update_current);    Bitmap Bitmap = Bitmapfactory.decoderesource (Getresources (), r.drawable.ic_launcher);             Notifybuilder = new Notificationcompat.builder (this)/* Set large icon*/. Setlargeicon (bitmap) /* Set small icon*/. Setsmallicon (r.drawable.ic_launcher)/* Set title*/. Setcontenttitle (" Notification ")/* Set verbose text */. Setcontenttext (" Hello World ")/* Set the time for notification to be the system time at which the notification was issued */. SETW Hen (System.currenttimemillis ())/* Set alert at status bar when notification is issued.Setticker ("Blessings from the asking month")/*setongoing (Boolean) set to True,notification will not be able to be cleared by left and right swipe * can be used to add resident notifications, you must call the Cancle method to clear the */ . Setongoing (TRUE)/* Set notification disappears after click */. Setautocancel (TRUE)//* Set the display of the number of notifications similar to the QQ kind, used for gay merger *    /. Setnumber (2)/* Click to jump to mainactivity*/. Setcontentintent (pendingintent); Manager.notify (121, Notifybuilder.build ());}

The comments in the code are very detailed, and the previous introduction is believed to be understandable.

3. Create a notification that displays bitmap, similar to how the screen looks

/**

* Similar to the system effect * * @param view */public void comnotification (view view) {/*    instantiate Notificationmanager for system service */    manager = (Notificationmanager) Getsystemservice (notification_service);    /* Get bitmap*/    Bitmap Bitmap = Bitmapfactory.decoderesource (Getresources (), r.drawable.ic_launcher);    Notifybuilder = new Notificationcompat.builder (this)/             * Set small icon*/            . Setsmallicon (R.drawable.ic_launcher )            /* Set title*/            . Setcontenttitle ("notifications")/            * Set verbose text */            . Setcontenttext ("Hello World")            . Setwhen ( System.currenttimemillis ())            . Setongoing (True)            . Setnumber (2);    Notificationcompat.bigpicturestyle Bigpicturestyle = new Notificationcompat.bigpicturestyle ();    Bigpicturestyle.bigpicture (bitmap);    Notifybuilder.setstyle (Bigpicturestyle);    Manager.notify (121, Notifybuilder.build ());}

The only thing to note here is that loading pictures is best not done on the UI thread (just for demonstration purposes).

4. Create a notification that resembles a calendar event and interact with the service.

/** * Create a calendar event-like notification * @param view */public void add_action (view view) {    myintent = new Intent (getapplicatio Ncontext (), myintentservice.class);    Myintent.putextra (Myconstants.extra_message, "Blessings from the month of asking");    Myintent.setaction (myconstants.action_ping);    Myintent.putextra (Myconstants.extra_timer, +);    StartService (myintent);}

The Intentservice code is as follows, and you can extend intentservice here if you need to, and notice the overloads of the constructor for the Intentservice class, which is your path name in super.

Package Me.androiddemo.canglangwenyue.test;import Android.app.intentservice;import android.app.Notification; Import Android.app.notificationmanager;import Android.app.pendingintent;import Android.content.intent;import Android.support.v4.app.notificationcompat;import android.util.log;/** * Created by Canglangwenyue on 14-12-9. */public class Myintentservice extends Intentservice {private Notificationmanager manager;private String message; private int mmills; Notificationcompat.builder builder;public Myintentservice () {//The super call is required.    The background thread that Intentservice//starts are labeled with the string argument you pass. Super ("Me.androiddemo.canglangwenyuet.test");}    @Overrideprotected void Onhandleintent (Intent Intent) {message = Intent.getstringextra (myconstants.extra_message);    Mmills = Intent.getintextra (Myconstants.extra_timer, myconstants.default_timer_duration); Notificationmanager Notificationmanager = (notificationmanager) getsystemservice (Notification_service);    String action = Intent.getaction ();    Issuenotification (Intent,message);    if (Action.equals (myconstants.action_ping)) {issuenotification (intent,message);        }else if (action.equals (Myconstants.action_snooze)) {notificationmanager.cancel (myconstants.notification_id);    Issuenotification (Intent, "");    }else if (action.equals (Myconstants.action_dismiss)) {notificationmanager.cancel (myconstants.notification_id); }}private void Issuenotification (Intent Intent, String msg) {manager = (Notificationmanager) getsystemservice (notific    Ation_service);    Intent dissmissitent = new Intent (this,myintentservice.class);    Dissmissitent.setaction (Myconstants.action_dismiss);    Pendingintent disintent = Pendingintent.getservice (this,0,dissmissitent,0);    Intent snoozeintent = new Intent (this,myintentservice.class);    Snoozeintent.setaction (Myconstants.action_snooze); Pendingintent snoopintent = Pendingintent.getservice (this,0,snoozeintent,0); Builder = new Notificationcompat.builder (this). Setsmallicon (r.drawable.ic_launcher). setcontenttitl E ("Information"). Setcontenttext ("Lalallalala"). SetDefaults (Notification.default_all). s Etstyle (New Notificationcompat.bigtextstyle (). BigText (msg)). Addaction (R.drawable.ic_launcher, "Dismiss", DisIn    Tent). Addaction (R.drawable.ic_launcher, "snooze", snoopintent);    Intent resultintent = new Intent (this,mainactivity2.class);    Resultintent.putextra (MYCONSTANTS.EXTRA_MESSAGE,MSG); Resultintent.setflags (Intent.flag_activity_new_task |    Intent.flag_activity_clear_task); Pendingintent resultpendingintent = pendingintent.getactivity (this,0,resultintent,pendingintent.flag_update_    Current);    Builder.setcontentintent (resultpendingintent);    Manager.notify (Myconstants.notification_id,builder.build ()); Starttimer (mmills);} private void Starttimer (int mmills) {try {thread.sleep (mmills);    }catch (Exception e) {log.d (Myconstants.debug_tag, "ERROR"); } issuenotification (builder);} private void Issuenotification (Notificationcompat.builder Builder) {manager = (Notificationmanager) getsystemservice (    Notification_service); Manager.notify (Myconstants.notification_id,builder.build ());}}

Here just a simple timer is implemented. Please refer to it for a moment.

5. Create a custom notification, as long as the remoteviews to get your XML layout file, and through the. SetContent (remoteviews) just fine, everyone just need to compare the differences.

 /** * Custom Notification style * * @param view */public void cus_notification (view view) {Toast.maketext (Mainactivity.this,    "AHa", Toast.length_long). Show ();    /* Instantiate Notificationmanager to get system service */manager = (Notificationmanager) getsystemservice (Notification_service);    Remoteviews remoteviews = new Remoteviews (Getpackagename (), r.layout.customnotification);    Remoteviews.setimageviewresource (R.id.imageview, R.DRAWABLE.PSB);    Remoteviews.settextviewtext (R.id.textview, "Your Haven");    Remoteviews.settextviewtext (R.id.textview2, "YUI");    Remoteviews.settextviewtext (R.ID.TEXTVIEW3, "watercress-fnm-my Hearts MHZ");    Remoteviews.setviewvisibility (R.id.my_large_button, view.visible); Notifybuilder = new Notificationcompat.builder (this). SetContent (Remoteviews). Setcontentintent (GetD             Efalutintent (notification.flag_auto_cancel)/* Set small icon*/. Setsmallicon (R.drawable.ic_launcher)            /* Set title*/. Setcontenttitle ("Notifications")/* Set verbose text */. Setticker ("Your Haven"). Setcontenttext ("Hello World"). Setwhen (System.curren    Ttimemillis ()). SetPriority (Notification.priority_default)//Set the notification priority. Setongoing (TRUE);    Notification noty = Notifybuilder.build ();    Noty.contentview = Remoteviews; Manager.notify (313, noty);}

Here just add a imageview and three TextView, you can further expand, such as add ImageButton, and through the broadcastreceiver to listen.

6. Finally write a notification bar with progress bar indicator, here you should understand what is called the differences, haha. As for other notification, such as fullscreen under the notification or lockscreen notification, are the same, everyone just set the appropriate properties on demand, the specific can query the official documents.

/** * Notification * with progress bar * @param view */public void pro_notification (view view) {manager = (Notificationmanager) getsy    Stemservice (Notification_service);    Notifybuilder = new Notificationcompat.builder (this); Notifybuilder.setcontenttitle ("Picture Download"). Setcontenttext ("Download in Progress"). Setongoin G (True). Setsmallicon (R.drawable.ic_launcher);//Start a lengthy operation in a background thread new thread                    (New Runnable () {@Override public void run () {int incr;                        Do the ' lengthy ' Operation times for (incr = 0; incr <=; incr + = 5) { Sets the progress indicator to a max value, the//current completion Percen Tage, and "determinate"//State notifybuilder.setprogress (INCR, False)                        ; Displays the Progress BAR for the first time.                        Manager.notify (0, Notifybuilder.build ());                            Sleeps the thread, simulating an operation//that takes time try {                        Sleep for 5 Seconds thread.sleep (5 * 1000);                        } catch (Interruptedexception e) {log.d ("NOTIFICATION", "Sleep Failure"); }}//When the loop is finished, updates the notification no                            Tifybuilder.setcontenttext ("Download complete")//Removes the progress bar                    . setprogress (0, 0, false);                Manager.notify (213, Notifybuilder.build ()); }}//starts the thread by calling the run () method in its Runnable). Start ();

Probably explain that is in an asynchronous thread inside every 5 seconds to increase the notification process 5, after the loop, after the re-add a notification to show the download is complete. As for the progress there are other ways to set up, here is not introduced, the actual use can be passed to the specific download progress.

Well, the feeling has been written a lot more, finally to summarize the use of notification it.
(i) A notification implementation can be obtained by following several steps:

1. Obtain the Notificationmanager instance, that is, the status notification bar management rights;

/* Instantiate Notificationmanager to get system service */manager = (Notificationmanager) getsystemservice (Notification_service);

2. Instantiating the notification constructor

Notifybuilder = new Notificationcompat.builder (this)

3. Set various properties for Notifybuilder

/** * The first three properties must be set *            //////* Set small icon*/. Setsmallicon (R.drawable.ic_launcher)//            set title*/            . Setcontenttitle ("Notifications")/            * Set verbose text */            . Setcontenttext ("Hello World")/             * Set the time for notification to be the system time at which the notification was issued */            . Setwhen (System.currenttimemillis ())/             * Set alert at status bar when notification is issued */            . Setticker ("Blessings from Ask the Moon")/             * Set the click Notification disappears */            . Setautocancel (True)                    /** * The default effect of setting Notification has the following notification.default_all: Ringtones, flashes, vibrations are system default. Notification.default_sound: System default ringtone. Notification.default_vibrate: System default vibration. Notification.default_lights: System default Flash. */            . SetDefaults (notification.default_vibrate)             /*setongoing (Boolean) set to True,notification will not be cleared by left and right swipe * Can be used to add resident notifications, you must call the Cancle method to clear */            . Setongoing (TRUE)/             * Set the number of notifications similar to the QQ kind, used for Comrade's merger *            /. Setnumber (2);

4. Display notification

       Manager.notify (Notifybuilder.build ());

(b) Some of the commonly used attribute functions

. setdefaults (int defaults)
The simplest, default (defaults) attribute used to add sound, strobe, and vibration effects to notifications, as written in the code above.

. setvibrate (long[] pattern)
To set whether to turn on vibrate, true to turn on

. Setsound (Uri Sound)
Used to set notification ringtones

. setpriority (int pri)
Used to set the priority, as well as a detailed explanation before

. Setongoing (Boolean ongoing)
If set to true, notifications for the resident notification bar are similar to the effects of ink weather.

setprogress (int max, int progress,boolean indeterminate)
In the notification for setting the progress

Android notification fully parse "go"

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.