Complete notification parsing for android Development
Complete notification parsing for android Development
This article mainly introduces how to use notification. by reading this article, you can understand how to use notification in android development. The notification in this article is mainly for versions earlier than Android 4.4.
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. Cannot be deleted by sliding left or right
/*** 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 threadnew Thread (new Runnable () {@ Overridepublic void run () {int incr; // Do the "lengthy" operation 20 timesfor (incr = 0; incr <= 100; incr + = 5) {// Sets the progress indicator to a max value, the // current completion percentage, and "determinate" // statenotifyBuilder. 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 timetry {// Sleep for 5 secondsThread. sleep (5*1000);} catch (InterruptedException e) {Log. d ("NOTIFICATION", "sleep failure") ;}// When the loop is finished, updates the notificationnotifyBuilder. 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) is 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) is used to set whether to enable vibration. true is enabled.
. SetSound (Uri sound) is used to set notification ringtones
. SetPriority (int pri) is used to set priority, which is also described in detail earlier.
. If setOngoing (boolean ongoing) 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