Android Notifications (Notification) using the detailed

Source: Internet
Author: User

This blog explains the use of the notification prompt message to the user in Android, notification is a global effect notification, the program generally through the Notificationmanager service to send notification. In this blog, we will describe the general use of notification, as well as the use of custom methods, for each of the different ways to provide an example of how to show the effect.

Notification

Notification, commonly known as notification, is a global effect of the notification, it is displayed at the top of the screen, the first will be represented as an icon form, when the user downward swipe down, show the specific content of the notification.

Note: Because of some compatibility issues with Android versions, for notification, Android3.0 is a watershed, and it is recommended to use Notification.builder build before it is built notification, and Notificationcompat.builder build is generally recommended after Android3.0. All of the code environments in this article are completed in 4.3, and if you use a 4.1-bit device test, be aware of compatibility issues.

Notifications are typically done by sending a notification object through the Notificationmanager service, Notificationmanager is an important system-level service that resides in the application's framework layer. The application can send global notifications through it like a system. At this point, you need to create a notification object that hosts the content of the notification. But generally in the actual use process, generally not directly constructs the notification object, Instead, it uses an inner class of Notificationcompat.builder to instantiate an object (using Notification.builder under Android3.0) and to set various properties of the notification, finally through Notificationcompat.build The Er.build () method gets a notification object. Once you have this object, you can use the Notificationmanager.notify () method to send notifications.

The Notificationmanager class is a notification Manager class, which is a service maintained by the system and is obtained in singleton mode, so this object is not typically instantiated directly. In Activity, you can use the Activity.getsystemservice (string) method to get the Notificationmanager object, Activity.getsystemservice (String) The method can return the corresponding object through the handle of the Android system-level service. You need to return Notificationmanager here, so you can pass the Context.notification_service directly.

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:


? Small icons, set using the Setsamllicon () method.
Title, set with the Setcontenttitle () method.
? text content, set using the Setcontenttext () method.

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);



pendingintent

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 to talk about 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 to deal with the immediate intention. For notifications, it is a system-wide global notification and does not determine when the intent is to be executed. When executing pendingintent outside the app, because it holds the context that triggers the app, the external app can execute the intent in Pendingintent if the current app does, even if the app that triggered the notification does not already exist. Intent can also be executed through the presence of the context in the pendingintent, and also handle the additional information that intent brings.

Pendingintent provides a number of static getxxx () methods for obtaining Pendingintent objects that are suitable for different scenarios. Typically, several parameters that need to be passed are general, and only one flag parameter is used to identify the construction selection of the pendingintent:

? Flag_cancel_current: If the built pendingintent already exists, then cancel the previous one and rebuild one.
? Flag_no_create: If the previous pendingintent no longer exists, it will not be built.
? Flag_one_shot: Indicates that the pendingintent built here can only be used once.
? Flag_update_current: If the built pendingintent already exists, replace it, often.

Notification visual style

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.

As the official document shows, a standard view is displayed at a height of 64dp and width as the screen standard. The notification body content of the standard view has a few:



    • The notification title.
    • Large icons.
    • Notification content.
    • The notification message.
    • Small icons.
    • The notification time, typically the system time, can also be set using the Setwhen ().
Here's an example that mimics the notification of the effect above.

  1. Btnnotification.setonclicklistener (New View.onclicklistener () {

  2. @Override
  3. public void OnClick (View v) {
  4. Bitmap BTM = Bitmapfactory.decoderesource (Getresources (),
  5. R.DRAWABLE.MSG);
  6. Notificationcompat.builder Mbuilder = new Notificationcompat.builder (
  7. mainactivity.this). Setsmallicon (R.DRAWABLE.MSG)
  8. . Setcontenttitle ("5 new Message")
  9. . Setcontenttext ("[email protected]");
  10. Mbuilder.setticker ("New message");//display on the notification bar the first time the message is prompted
  11. Mbuilder.setnumber (12);
  12. Mbuilder.setlargeicon (BTM);
  13. Mbuilder.setautocancel (TRUE);//The disappearance of own maintenance notifications

  14. Build a intent
  15. Intent resultintent = new Intent (Mainactivity.this,
  16. Resultactivity.class);
  17. Encapsulation of a intent
  18. Pendingintent resultpendingintent = pendingintent.getactivity (
  19. Mainactivity.this, 0, Resultintent,
  20. Pendingintent.flag_update_current);
  21. Set the intent of the notification topic
  22. Mbuilder.setcontentintent (resultpendingintent);
  23. Get Notification Manager Object
  24. Notificationmanager Mnotificationmanager = (notificationmanager) getsystemservice (Context.notification_service);
  25. Mnotificationmanager.notify (0, Mbuilder.build ());
  26. }
  27. });
Copy Code
Display effect:



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:



SetStyle () passes a Notificationcompat.style object, which is an abstract class, and Android provides us with three implementation classes for displaying different scenarios. respectively:

    • Notificationcompat.bigpicturestyle, displays a 256dp height bitmap in the detail section.
    • Notificationcompat.bigtextstyle, displays a large block of text in the detail section.
    • Notificationcompat.inboxstyle, displays a line of text in the detail section.
If you only display a picture, use Bigpicturestyle is the most convenient, if you need to display a rich text information, you can use Bigtextstyle; if you only want to display information for one text, use Inboxstyle. Later, an example is used to demonstrate the use of inboxstyle, mimicking the display of the above image.

Implementation code:
    Btnbigviewnotification.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {    Bitmap BTM = Bitmapfactory.decoderesource (Getresources (), r.drawable.msg);    Intent Intent = new Intent (mainactivity.this, Resultactivity.class); Pendingintent pendingintent = pendingintent.getactivity (mainactivity.this, 0, intent, pendingintent.flag_cancel_cur    RENT); Notification Noti = new Notificationcompat.builder (mainactivity.this). Setsmallicon (r.drawable.msg). Setlargeico N (BTM). Setnumber. Setcontentintent (pendingintent). SetStyle (New Notificationcompat.inboxstyle (). Addl    INE ("M.twain (Google +) Haiku is more than a cert ...")    . AddLine ("M.twain Reminder"). AddLine ("M.twain Lunch?") . AddLine ("M.twain revised Specs"). AddLine ("M.twain"). AddLine ("Google Play celebrate billion apps with Goo. .")    . AddLine ("Stack Exchange stackoverflow weekly NEWSL ..."). Setbigcontenttitle ("6 new MEssage "). Setsummarytext (" [email protected] "). Build ();    Notificationmanager Mnotificationmanager = (notificationmanager) getsystemservice (Context.notification_service);    Mnotificationmanager.notify (0, Noti); }    });


Display effect:



notification of a progress bar style

For a standard notification, sometimes the message displayed is not necessarily static, and a progress bar can be set to show the progress of the transaction completion.

The Notification.builder class provides a setprogress (int max,int Progress,boolean indeterminate) method for setting the progress bar, which Max uses to set the maximum number of progress, The progress is used to set the current progress, indeterminate is used as a progress bar to determine progress. With the indeterminate setting, you can implement two different styles of progress bars, one with progress (false) and one for cyclic flow (false). The following is a demonstration of two examples:

A progress bar, implementing the Code:

    Btnprogrenotification.setonclicklistener (New View.onclicklistener () {    @Override public    void OnClick (View v) {    manager = (Notificationmanager) getsystemservice (context.notification_service);    Builder = new Notificationcompat.builder (mainactivity.this)    . Setsmallicon (R.drawable.ic_launcher)    . Setcontenttitle ("Picture Download")    . Setcontenttext ("Download in Progress");    Builder.setautocancel (true);    Dynamically increases the progress bar scale by a child thread    new Thread (new Runnable () {    @Override public    void Run () {    int incr;    for (incr = 0; incr <=, incr + = 5) {    builder.setprogress (+, incr, false);    Manager.notify (0, Builder.build ());    try {    thread.sleep;    } catch (Interruptedexception e) {    log.i (TAG, "Sleep Failure");}    }    Builder.setcontenttext ("Download complete")    . Setprogress (0, 0, false);    Manager.notify (0, Builder.build ());    }    ). Start ();    }    });



Display effect:



For the Loop flow progress bar, here is the implementation code:
    Btnpronotification.setonclicklistener (New View.onclicklistener () {    @Override public    void OnClick (View v) {    manager = (Notificationmanager) getsystemservice (context.notification_service);    Builder = new Notificationcompat.builder (mainactivity.this)    . Setsmallicon (R.drawable.ic_launcher)    . Setcontenttitle ("Picture Download")    . Setcontenttext ("Download in Progress");    Builder.setprogress (0, 0, true);//set to True to indicate flow    manager.notify (0, Builder.build ());    After 5 seconds, the new Thread is stopped (    new Runnable () {    @Override public    void Run () {    try {    Thread.Sleep ( );    } catch (Interruptedexception e) {    e.printstacktrace ();    }    Builder.setprogress ([+], false);//set to True, indicating scale    manager.notify (0, Builder.build ());}    }). Start ();    }    });


Effect Show:



Custom Notifications

As with toast, notifications can also use custom XML to customize styles, but for notifications, because it's global, it's not easy to inflate a view through inflate, because when notifications are triggered, the response app is closed and cannot get the XML layout file specified. Therefore, you need to use a separate Remoteviews class to operate.

Remoteviews, which describes the structure of a view hierarchy, can be displayed in another process. Hierarchies also "inflate" out a view from a layout file, which provides some basic operations to change the content of its bloat.

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.

Here's an example to show it:

Custom Layout XML code:

    <relativelayout    android:layout_width= "match_parent"    android:layout_height= "Match_parent    " android:padding= "10DP" >    <imageview    android:id= "@+id/imageno"    android:layout_width= "Wrap_ Content "    android:layout_height=" match_parent "    android:layout_alignparentleft=" true "    android:layout _marginright= "10DP"/>    <textview    android:id= "@+id/titleno" android:layout_width= "Wrap_    Content "    android:layout_height=" wrap_content "    android:layout_torightof=" @id/imageno "/>    < TEXTVIEW    android:id= "@+id/textno"    android:layout_width= "wrap_content"    android:layout_height= " Wrap_content "    android:layout_below=" @id/titleno "    android:layout_torightof=" @id/imageno "/>



Implementation code:

    Btncustomnotification.setonclicklistener (New View.onclicklistener () {@Override public void OnClick (View v) {    Remoteviews contentviews = new Remoteviews (Getpackagename (), r.layout.custom_notification);    The property is set by the control's ID contentviews. Setimageviewresource (R.id.imageno, R.DRAWABLE.BTM1);    Contentviews.settextviewtext (R.id.titleno, "custom notification title");    Contentviews.settextviewtext (R.id.textno, "Custom notification content");    Intent Intent = new Intent (mainactivity.this, Resultactivity.class); Pendingintent pendingintent = pendingintent.getactivity (mainactivity.this, 0, intent, pendingintent.flag_cancel_cur    RENT); Notificationcompat.builder Mbuilder = new Notificationcompat.builder (mainactivity.this). SetSmallIcon (R.drawable.ic    _launcher). Setcontenttitle ("My notification"). Setticker ("new Message");    Mbuilder.setautocancel (TRUE);    Mbuilder.setcontentintent (pendingintent);    Mbuilder.setcontent (contentviews);    Mbuilder.setautocancel (TRUE); NotificationmanagEr mnotificationmanager = (notificationmanager) getsystemservice (Context.notification_service);    Mnotificationmanager.notify (Mbuilder.build ()); }    });


Effect Show:



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.
On Android, if you need to access a hardware device, you need to authorize it, so you need to add two authorizations in the manifest file Androidmanifest.xml, respectively, to grant access to the vibrator and Flash:

    <!--Flash rights    --<uses-permission android:name= "Android.permission.FLASHLIGHT"/>    <!--vibrator Permissions-- >    <uses-permission android:name= "Android.permission.VIBRATE"/>



Because it's just a property setting, and most of the time, using the system settings, there's no code sample available.

Summary

Notifications are a common feature of Android that keeps your app alive and provides the possibility to interact with users when they don't have access to the app.

Android Notifications (Notification) using the detailed

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.