Complete android notification Parsing
Events in Android 4.4 and Lower
Notification is an important part. It is closely related to services, BroadcastReceiver, and Intent. Using notification can greatly increase the activity of your app compared with apps without notification.
It is obvious that this article will detail the notification of 4.4 and below. As for the features of android 5.0, I plan to write a special series during the holidays. Download should be a review of knowledge. After all, let's learn about new things in a gentle manner. Haha.
The notification system allows your app to keep the user informed about events, such as new chat messages or a calendar event. 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 is not paying attention.
Notification allows your app to notify users of events in the app, such as a new message or calendar event. It can be considered that notification is a news channel used to notify users of important events when they do not notice it.
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 the minimum, all communications are made up of the basic layout, including:
The icon of the application that sends the notification or the image of the sender.
The title and message of notification.
Timestamp
When the main icon is used to display the sender's image, the Secondary icon is used to display the icon for sending the application.
Expanded layoutsYou have 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 two expanded layout templates (text and image) for you to 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 rows of a message or preview an image. This provides additional content for the user and, in some cases, allows the user to read the complete information. You can use pinch-zoom or double-finger sliding to open the expanded layout. Android provides two extended layout methods (image and text) for a single notification for your application.
1. notification title
2. the icon of the application that sends the notification or the image of the sender.
3. notification message
4. display the number of notifications
5. When the main icon is used to display the sender's image, the Secondary icon is used to display the icon for sending the application.
6. timestamp. The default time is the time when the system sends a notification.
Actions
Android supports optional actions that are 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 without having to open the originating application. This speeds up interaction and, in conjunction with "swipe-to-dismiss", helps users to streamline their notification triaging experience.Be judicious with how many actions you include with a notification. The more actions you 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 ones.Good candidates for actions on notifications are actions that are:essential, frequent and typical for the content type you'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 display of optional operations at the point of notification. With these actions, you can process most of the same tasks without opening the application. This set of happy interaction speeds, combined with slide disappears, allows users to simplify their notification processing experience.
It is wise to decide the number of actions placed in your notification. If you include more actions, you will increase the complexity of interaction. Select one or two important and meaningful actions.
A good candidate action has the following features:
. Typical and frequently used actions that are important to this notification.
. Time is tight
. Do not overlap with adjacent actions.
Do not:
. Ambiguous
. It is the same as the action for clicking notification (such as "Read" or "Open ")
Design guidelines
. Personalization
. Navigate to the correct place
Correctly set the notification priority.
Let's take a look at priority settings. For other explanations, refer to the official website.
SetPriority (int pri) is used to specify the priority.
The corresponding attributes are as follows:
Notification. PRIORITY_DEFAULT (priority is 0)
Notification. PRIORITY_HIGH
Notification. PRIORITY_LOW
Notification. PRIORITY_MAX (Priority: 2)
Notification. PRIORITY_MIN (Priority:-2)
Now let's take a look at how to implement a notification. It is estimated that the most common practice is as follows:
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 to start a notification in the service, but you must remember that this method is outdated. That is to say, Google does not advocate this method to start a notification. Icationicationcompat. Builder under the V4 package is recommended officially, so that we can set various attributes.
Now let's take a look at the specific implementation of Notification.
1. Create a simple notification.
Required notification contentsnotification must contain A Notification object must contain the following: A notification must contain the following attributes: A small icon, set by setSmallIcon () A small icon, use setSmallIcon () to set it. It corresponds to region A title in Region 2, set by setContentTitle (), and uses setContentTitle () to set it. It corresponds to Region 1 Detail text, set by setContentText () detailed text, set with setContentText (), corresponding to Area 3 in
These three parameters must be set. Other extensions depend on requirements. The Code is as follows:
Private icationicationmanager manager; NotificationCompat. builder yybuilder; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main);/* instantiate icationicationmanager to obtain the System Service */manager = (NotificationManager) getSystemService (NOTIFICATION_SERVICE);}/*** display the simplest notification, the three set methods in the following method must be set ** @ param view */public void simNotification (View view) {Toast. makeText (this, "hha", Toast. LENGTH_LONG ). show (); yybuilder = new NotificationCompat. builder (this)/* Set small icon */. setSmallIcon (R. drawable. ic_launcher)/* Set title */. setContentTitle ("notification")/* set detailed text */. setContentText ("Hello world"); manager. notify (100, notifyBuilder. build ());}
The comments in the Code are very detailed, and simNotification is bound to a Button. In this way, we have implemented the simplest notification.
2. Create a Notification to jump to another Activity.
/*** Click to jump to the specified Activity ** @ param view */public void largePicture (View view) {/* instantiate icationicationmanager to get system services */manager = (icationicationmanager) getSystemService (icationication_service); // click the Intent ACTION to jump to 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); yybuilder = new NotificationCompat. builder (this)/* set large icon */. setLargeIcon (bitmap)/* Set small icon */. setSmallIcon (R. drawable. ic_launcher)/* Set title */. setContentTitle ("notification")/* set detailed text */. setContentText ("Hello world")/* set the notification time to the system time when the notification is sent */. setWhen (System. currentTimeMillis ()/* sets the status bar when a notification is sent */. setTicker ("blessings from months")/* setOngoing (boolean) is set to true, and notification cannot be cleared by sliding left and right * can be used to add resident notifications, the cancle method must be called to clear */. setOngoing (true)/* indicates that the notification disappears after the setting is clicked */. setAutoCancel (true)/* set the display of the number of notifications, which is similar to that of QQ. It is used for merging comrades */. setNumber (2)/* click to jump to MainActivity */. setContentIntent (pendingIntent); manager. notify (121, notifyBuilder. build ());}
The comments in the Code are very detailed. I believe you can understand them with the previous introduction.
3. Create a notification to display bitmap, which is similar to the display effect of the screen.
/*** System-like effect ** @ param view */public void comNotification (View view) {/* instantiate icationicationmanager to obtain system services */manager = (icationicationmanager) getSystemService (icationication_service);/* Get bitmap */Bitmap bitmap = BitmapFactory. decodeResource (getResources (), R. drawable. ic_launcher); yybuilder = new NotificationCompat. builder (this)/* Set small icon */. setSmallIcon (R. drawable. ic_launcher)/* Set title */. setContentTitle ("notification")/* set detailed text */. setContentText ("Hello world "). setWhen (System. currentTimeMillis ()). setOngoing (true ). setNumber (2); icationicationcompat. bigPictureStyle bigPictureStyle = new NotificationCompat. bigPictureStyle (); bigPictureStyle. bigPicture (bitmap); yybuilder. setStyle (bigPictureStyle); manager. notify (121, notifyBuilder. build ());}
The only thing to note here is that it is best not to load images in the UI thread (this is only for demonstration ).
4. Create a notification similar to a calendar event and interact with the Service.
/*** Create a notification * @ param view */public void add_action (View view) similar to a calendar event {myIntent = new Intent (getApplicationContext (), MyIntentService. class); myIntent. putExtra (myConstants. EXTRA_MESSAGE, "blessings from the question month"); myIntent. setAction (myConstants. ACTION_PING); myIntent. putExtra (myConstants. EXTRA_TIMER, 1000); startService (myIntent );}
The IntentService code is as follows. You can extend the IntentService here when necessary. Pay attention to the heavy load of the constructor of the IntentService class. Your path name is 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 is 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(NOTIFICATION_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) .setContentTitle("Information") .setContentText("lalallalala") .setDefaults(Notification.DEFAULT_ALL) .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)) .addAction(R.drawable.ic_launcher, "Dismiss", disIntent) .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 is just a simple Timer. For more information, see.
5. Create a custom notification. You only need to use RemoteViews to retrieve your XML layout file and use. setContent (remoteViews) 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 icationicationmanager to obtain system services */manager = (icationicationmanager) 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, "-FNM- MHZ"); remoteViews. setViewVisibility (R. id. my_large_button, View. VISIBLE); policybuilder = new NotificationCompat. builder (this ). setContent (remoteViews ). setContentIntent (getDefalutIntent (Notification. FLAG_AUTO_CANCEL)/* Set small icon */. setSmallIcon (R. drawable. ic_launcher)/* Set title */. setContentTitle ("notification")/* set detailed text */. setTicker ("Your Haven "). setContentText ("Hello world "). setWhen (System. currentTimeMillis ()). setPriority (Notification. PRIORITY_DEFAULT) // sets the priority of the notification. setOngoing (true); Notification noty = policybuilder. build (); noty. contentView = remoteViews; manager. notify (313, noty );}
Here we only add an ImageView and three textviews. You can further expand them, for example, add ImageButton and listen through BroadcastReceiver.
6. At last, write a notification with a progress bar indicator. Here, you should understand what it means to save exceptions. Haha. For other notifications, such as the notification under FullScreen or the notification of LockScreen, the change is not changed. You only need to set the corresponding attributes as needed. For details, refer to the official documentation.
/*** Notification with progress bar * @ param view */public void Pro_Notification (View view) {manager = (icationicationmanager) getSystemService (icationication_service); policybuilder = new NotificationCompat. builder (this); policybuilder. setContentTitle ("Picture Download "). setContentText ("Download in progress "). setOngoing (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 20 times for (incr = 0; incr <= 100; incr + = 5) {// Sets the progress indicator to a max value, the // current completion percentage, and "determinate" // state policybuilder. setProgress (100, 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 policybuilder. 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 ();}
In a general explanation, the process of notification is increased by 5 every five seconds in an asynchronous thread. After the loop ends, a new notification is added to show that the download is complete. There are other methods to set the progress. We will not describe them here. You can enter the specific download progress in actual use.
Well, I feel that I have already written much better. Let's summarize the usage of notification.
(1) follow these steps to implement a notification:
1. Obtain the icationicationmanager instance to obtain the status notification bar management right;
/* Instantiate icationicationmanager to obtain the System Service */manager = (NotificationManager) getSystemService (NOTIFICATION_SERVICE );
2. instantiate the constructor of notification
notifyBuilder = new NotificationCompat.Builder(this)
3. Set various attributes for yybuilder
/*** The first three attributes must be set * // * the small icon */. setSmallIcon (R. drawable. ic_launcher)/* Set title */. setContentTitle ("notification")/* set detailed text */. setContentText ("Hello world")/* set the notification time to the system time when the notification is sent */. setWhen (System. currentTimeMillis ()/* sets the status bar when a notification is sent */. setTicker ("Greetings from ")/* indicates that the notification disappears after you click Set */. setAutoCancel (true)/*** set the default Effect of notification to the following types of Notification. DEFAULT_ALL: The system defaults to ringtones, flashes, and vibrations. Notification. DEFAULT_SOUND: the system's default ringtone. Notification. DEFAULT_VIBRATE: default system vibration. Notification. DEFAULT_LIGHTS: System Default flash. */. SetDefaults (Notification. DEFAULT_VIBRATE)/* setOngoing (boolean) is set to true, notification cannot be cleared by sliding left or right * can be used to add resident notifications, you must call the cancle method to clear */. setOngoing (true)/* set the display of the number of notifications, which is similar to QQ, used for the combination of comrades */. setNumber (2 );
4. Display notification
manager.notify(100, notifyBuilder.build());
(2) Some common attribute functions
. SetDefaults (int defaults)
The easiest way to add sound, flashing, and vibration effects to a notification. Use the default (defaults) attribute, which is written in the above Code.
. SetVibrate (long [] pattern)
Used to set whether to enable vibration. true is enabled.
. SetSound (Uri sound)
Used to set notification ringtones
. SetPriority (int pri)
It is used to set priority, which is also explained in detail earlier
. SetOngoing (boolean ongoing)
If it is set to true, the notification in the resident notification bar is similar to the effect of moji weather.
SetProgress (int max, int progress, boolean indeterminate)
In the notification used to set the progress
Well, let's write this today, and finally attach the demo. Http://download.csdn.net/detail/u010835702/8241469