Do you really know Android notification?

Source: Internet
Author: User
Tags deprecated home screen

Recently from time to time someone asked me how to achieve such or such a notice, so this article will be based on personal experience on the notification to do a summary, for reference!

What is notification (Notification)

A notification is a message that can be displayed to a user outside of the normal user interface of the application.
When the notification is issued, it first comes out in the notification area of the status bar, and the user opens the notification drawer to view the notification details. Both the notification area and the notification drawer are system control areas that the user can view at any time.

As an important part of the Android user interface, notifications have their own design guidelines. The changes to the Material design introduced in Android 5.0 (API level 21) are particularly important, and for more information please read the Notification Design Guide.

How to create a notification

As the Android system continues to evolve, the way notification is created changes, with the following major changes:

before Android 3.0

Before Android 3.0 (API level 11), use the new Notification() way to create notifications:

    NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);    PendingIntent contentIntent = PendingIntent.getActivity(this0new Intent(this0);    new Notification(icon, tickerText, when);    notification.setLatestEventInfo(this, title, content, contentIntent);    mNotifyMgr.notify(NOTIFICATIONS_ID, notification);
Android 3.0 (API level 11) and later

Android 3.0 begins to be deprecated new Notification() and instead uses Notification.Builder() to create notifications:

 Notificationmanager mnotifymgr = (notificationmanager) getSystemService ( Notification_service); Pendingintent contentintent = pendingintent.getactivity (this , 0 , new  Intent (this , Resultactivity.class), 0 ); Notification Notification = new  notification.builder ( This ). Setsmallicon (R.drawable.notification_icon). Setcontenttitle (" My notification "). Setcontenttext (" Hello world! ") . Setcontentintent (Contentintent). build (); //getnotification () deprecated in API level  mnotifymgr.notify (notifications_id, notification); 

Note here: "Build ()" is a Androdi 4.1 (API level 16) to replace "getnotification ()". API level 16 starts to discard "getnotification ()"

compatible with versions prior to Android 3.0

This workaround is provided in order to be compatible with API level 11 previous versions v4 Support Library NotificationCompat.Builder() . It Notification.Builder() 's not much different from the similarities.

NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, ResultActivity.class), 0);NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)            .setSmallIcon(R.drawable.notification_icon)            .setContentTitle("My notification")            .setContentText("Hello World!")            .setContentIntent(contentIntent);mNotifyMgr.notify(NOTIFICATIONS_ID, mBuilder.build());

Note: In addition to special instructions, this article will be based on Notificationcompat.builder () to expand the parsing, Notification.builder () similar.

Notification Basic Usage Required properties for notifications

A notification must contain the following three properties:

    • Small icons, corresponding to Setsmallicon ()
    • Notification title, corresponding to Setcontenttitle ()
    • For more information, correspond to Setcontenttext ()

Other properties are optional, for more property methods please refer to Notificationcompat.builder.

Although the others are optional, it is common to add at least one action (action) to the notification, which can be a jump to activity, start a service, or send a broadcas. Add an action to the notification in the following ways:

    • Using Pendingintent
    • Action Button via large view notification//support only Android 4.1 (API level 16) and later,
Create a notification

1. Instantiate a Notificationcompat.builder object

    new NotificationCompat.Builder(this)                .setSmallIcon(R.drawable.notification_icon)                .setContentTitle("My notification")                .setContentText("Hello World!");

Notificationcompat.builder default values that are set automatically:

    • Priority:priority_default
    • When:System.currentTimeMillis ()
    • Audio Stream:stream_default

2. Define and set a notification action (action)

    new Intent(this, ResultActivity.class);    PendingIntent resultPendingIntent = PendingIntent.getActivity(                this0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);    mBuilder.setContentIntent(resultPendingIntent);

3. Generating Notification objects

Notificatioin notification = mBuilder.build();

4. Use to NotificationManager send notifications

// Sets an ID for the notificationint mNotificationId = 001;// Gets an instance of the NotificationManager serviceNotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// Builds the notification and issues it.mNotifyMgr.notify(mNotificationId, notification);
Update Notifications

The update notification is simple enough to send a notification with the same ID again, and if the previous notification persists, the notification property is updated and re-created if the previous notification does not exist.
Example code:

Notificationmanager mnotifymgr = (notificationmanager) getsystemservice (Notification_service);//sets an ID for the notification, so it can be updated    intNotifyid =1; Notificationcompat.builder Mnotifybuilder =NewNotificationcompat.builder ( This). Setcontenttitle ("New Message"). Setcontenttext ("You ' ve received new messages."). Setsmallicon (R.drawable.ic_notify_status);intNummessages =0;//Start of a loop that processes data and then notifies the user... mnotifybuilder.setcontenttext ("New content text"). Setnumber (++nummessages);//Because The ID remains unchanged, the existing notification is updated.Mnotifymgr.notify (Notifyid, Mnotifybuilder.build ()); ...
Cancel Notification

There are 4 ways to cancel a notification:

    • Clicking the Clear button in the notification bar clears all notifications that can be cleared
    • A setautocancel () or Flag_auto_cancel notification is set, which is cleared when you click on the notification
    • Clear notification of the specified ID by calling the Cancel () method through Notificationmanager
    • Clearing all notifications sent before the app by calling the Cancelall () method with Notificationmanager
Notification Type Large View Notification

Notifications have two views: normal view and large view.
Normal view:

Large view:

By default, Normal view is available by NotificationCompat.Builder.setStyle() setting a large view.

Note: Large views are introduced by Android 4.1 (API level 16) and are only supported on Android 4.1 and later.

Building a large view notification

Consider the example:
1. Build the action button pendingintent

    new Intent(this, PingService.class);    dismissIntent.setAction(CommonConstants.ACTION_DISMISS);    PendingIntent piDismiss = PendingIntent.getService(this00);    new Intent(this, PingService.class);    snoozeIntent.setAction(CommonConstants.ACTION_SNOOZE);    PendingIntent piSnooze = PendingIntent.getService(this00);

2. Building Notificatoncompat.builder Objects

 Notificationcompat.builder Builder = new  notificationcompat.builder (this ). Setsmallicon (R.dra wable.ic_stat_notification). Setcontenttitle (GetString (r.string.notification)). Setcontenttext (getSt Ring (r.string.ping)). SetDefaults (Notification.default_all) //requires vibrate perm Ission  //This method is ignored before Android 4.1 . SetStyle (new  Notificationcompat.bigtextstyle (). BigText (msg)) //add action Button . Addaction (R.drawable.ic_stat_dismiss, getString (R.string.dis Miss), Pidismiss). Addaction (R.drawable.ic_stat_snooze, getString (r.string.snooze), Pisnooz e);  

3. Other steps are the same as normal view

Progress bar Notification
  • progress bar for Clear Progress
    Use setProgress(max, progress, false) to update the progress.
    Max: Max Progress value
    Progress: Current Progress
    False: Whether it is an ambiguous progress bar

    Simulate the download process, as shown in the following example:

        intID =1;    ... mnotifymanager = (Notificationmanager) getsystemservice (Context.notification_service); Mbuilder =NewNotificationcompat.builder ( This); Mbuilder.setcontenttitle ("Picture Download"). Setcontenttext ("Download in Progress"). Setsmallicon (r.drawable.ic_notification);//Start a lengthy operation in a background thread    NewThread (NewRunnable () {@Override             Public void Run() {intincr for(incr =0; INCR <= -; incr+=5) {mbuilder.setprogress ( -, INCR,false); Mnotifymanager.notify (ID, mbuilder.build ());Try{//Sleep for 5 secondsThread.Sleep (5* +); }Catch(Interruptedexception e) {LOG.D (TAG,"Sleep Failure"); }} mbuilder.setcontenttext ("Download Complete")//Download Complete. setprogress (0,0,false);//Remove progress barMnotifymanager.notify (ID, mbuilder.build ()); }}). Start ();


    Notification of progress bar notification and download completion for the download process, respectively.

  • progress bar for indeterminate progress
    setProgress(0, 0, true)a progress bar used to indicate an ambiguous progress

    Mbuilder.setprogress (0, 0, true); Mnotifymanager.notify (ID, mbuilder.build ());

Floating Notifications (heads-up notifications)

Android 5.0 (API level 21), notifications can be displayed in small windows when the screen is unlocked and lit. The user can operate the notification without leaving the current app.
:

NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(this)        .setContentTitle("New Message")        .setContentText("You‘ve received new messages.")        .setSmallIcon(R.drawable.ic_notify_status)        .setFullScreenIntent(pendingIntent, false);

Floating notifications are shown in the following two scenarios:

    • Setfullscreenintent (), as in the example above.
    • Notifications have high priority and use ringtones and vibrations
Lock Screen Notifications

Starting with Android 5.0 (API level 21), notifications can be displayed on the lock screen. The user can choose whether to allow sensitive notification content to be displayed on a secure lock screen by setting.
Your app can setVisibility() control the display level of notifications:

    • Visibility_private: Displays basic information, such as an icon for a notification, but hides the entire contents of the notification
    • Visibility_public: Displays the full contents of the notification
    • Visibility_secret: No content is displayed, including icons
Custom Notifications

The Android system allows you to customize notifications using Remoteviews.
The custom normal view notification height limit is 64DP, and the large view notification height limit is 256DP. At the same time, it is recommended to customize notifications as simple as possible to improve compatibility.

Custom notifications need to do the following:
1. Create a custom notification layout
2. Use remoteviews to define notification components, labels, text, etc.
3. Call to setContent() bind the Remoteviews object to Notificationcompat.builder
4, with the normal sending notification process

Note: Avoid setting the background for notifications, for compatibility reasons, some text may not be visible.

Define notification text styles

The background color of the notification varies between devices and versions, and Android2.3 begins with a set of standard notification text styles, which suggest that custom notifications use standard styles, which helps inform text to be visible.
Notification Text style:

Android 5.0之前可用:android:style/TextAppearance.StatusBar.EventContent.Title    // 通知标题样式  android:style/TextAppearance.StatusBar.EventContent             // 通知内容样式  Android 5.0及更高版本:  android:style/TextAppearance.Material.Notification.Title         // 通知标题样式  android:style/TextAppearance.Material.Notification                  // 通知内容样式  

For more information about the standard style and layout of notifications, refer to frameworks/base/core/res/res/layout the notification template under the source path such as:

Android 5.0之前:  notification_template_base.xml  notification_template_big_base.xml  notification_template_big_picture.xml  notification_template_big_text.xml  Android 5.0 及更高版本:  notification_template_material_base.xml  notification_template_material_big_base.xml  notification_template_material_big_picture.xml  notification_template_part_chronometer.xml  notification_template_progressbar.xml  等等。
Keep activity back stack General Activity

By default, starting an activity from the notification, pressing the back key will return to the home screen. But sometimes there is a need to press the return key to remain in the current application, which will be used TaskStackBuilder .

1. Define the relationship of activity in manifest

Android 4.0.3 及更早版本<activity    android:name=".ResultActivity">    <meta-data        android:name="android.support.PARENT_ACTIVITY"        android:value=".MainActivity"/></activity>Android 4.1 及更高版本<activity    android:name=".ResultActivity"    android:parentActivityName=".MainActivity"></activity>

2. Create return stack pendingintent

Intent resultIntent = new Intent(this, ResultActivity.class);TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);// 添加返回栈stackBuilder.addParentStack(ResultActivity.class);// 添加Intent到栈顶stackBuilder.addNextIntent(resultIntent);// 创建包含返回栈的pendingIntentPendingIntent resultPendingIntent =        stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);NotificationCompat.Builder builder = new NotificationCompat.Builder(this);builder.setContentIntent(resultPendingIntent);NotificationManager mNotificationManager =    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);mNotificationManager.notify(id, builder.build());

After the above operation, starting resultactivity from the notification, pressing the back key will return to Mainactivity instead of the home screen.

Special Activity

By default, activity initiated from the notification appears in the recent task list. If you do not need to display in a recent task, you need to do the following:

1. Define activity in manifest

<activity    android:name=".ResultActivity"    android:launchMode="singleTask"    android:taskAffinity=""    android:excludeFromRecents="true"></activity>

2. Build Pendingintent

NotificationCompat.Builder builder = new NotificationCompat.Builder(this);Intent notifyIntent = new Intent(this, ResultActivity.class);// Sets the Activity to start in a new, empty tasknotifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);PendingIntent notifyPendingIntent =        PendingIntent.getActivity(this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);builder.setContentIntent(notifyPendingIntent);NotificationManager mNotificationManager =    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);mNotificationManager.notify(id, builder.build());

After you start resultactivity from the notification, this activity does not appear in the recent Tasks list.

notification of common properties and constants How notifications are reminded

1. Sound Alert

    • Default Sound
      Notification.defaults |= Notification.default_sound;

    • Custom sounds
      Notification.sound = Uri.parse ("File:///sdcard0/notification.ogg");

2. Vibration Alert

    • Default Vibration
      Notification.defaults |= notification.default_vibrate;

    • Custom Vibration
      Long[] Vibrate = {100, 200, 300, 400}; Vibration effect
      Indicates that at 100, 200, 300, 400 these points of time alternately start and close the vibration notification.vibrate = vibrate;

3. Flashing Reminder

    • Default Flashing
      Notification.defaults |= notification.default_lights;

    • Custom Flashing
      Notification.ledargb = 0xff00ff00; Color of LED lights, green light
      NOTIFICATION.LEDONMS = 300; LED light display in milliseconds, 300 ms
      NOTIFICATION.LEDOFFMS = 1000; Number of milliseconds to turn off the LED light, 1000 ms
      Notification.flags |= notification.flag_show_lights; This sign must be added.

the common flags
    • Flag_auto_cancel
      When the notification is clicked by the user, it is automatically cleared (cancel)

    • Flag_insistent
      Repeat the reminder tone until the user responds

    • Flag_ongoing_event
      Represents an event that is running

    • Flag_no_clear
      Notification bar When you click the "Clear" button, the notification will not be cleared

    • Flag_foreground_service
      Indicates that the current service is a foreground service

More notification properties are described in notification.

That ' s all! More notification knowledge points await you to discover, welcome to add!

References
Notifications



Original articles, welcome reprint, reproduced please indicate the source

My Jane book account is Connorlin, welcome!

Please pay attention to my

Do you really know Android notification?

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.