Android System Application---One of notification: Notification Overview and use

Source: Internet
Author: User
Tags set time

The notification mechanism is an important means for Android and user interaction to improve app activity, which can be used to present important information to users, such as new chat messages or calendar events. Notification's design philosophy is not only to inform users of important information and will not interrupt the user's current behavior, if the information to focus on users, users will click to take the initiative to do related actions, for an app, notifications can not be abused, otherwise redundant message notification will only alienate your users.

Notice can be divided into toastnotification and statusbarnotification,toast relatively simple, our main research is statusbarnotification

functional function of notification

1. Display messages such as SMS, instant messages, etc. (such as QQ, SMS)

2. Display the push message of the client (if there is a new release, advertising, referral news, etc.)

3. Show what is going on (Programs running in the background, such as music player, download progress during version update, etc.)

Notification of the form of expression

After a notification arrives, it usually flashes a 5s ticker, then the status bar displays the notification icon, and the drop-down status bar displays the complete information of the message notification, such as sending a notification to notification to add sound, vibration, flash, and other functions to alert the user.

When the user clicks on the notification, the system initiates the corresponding activity based on the Intent that was passed in when the notification was created. The status bar notification should also be used when the background service needs to prompt the user to respond to an event. Background services should not start an activity on their own to interact with the user, it should create a status bar notification, when the user selects this notification to start the activity.

A status bar notification can be initialized in activity or service , but because activity can only take action when it runs in the foreground and gets the focus, generally we just use it as a test, so the status bar notification is usually created by the service.

Create and update a notification

Use the Notification class and the Notificationmanager class to create a status bar notification

The Notificationmanager class is a system service used to manage all notifications, through the Getsystemservice () method to obtain a reference to it. Use the Notification instance to configure a status bar notification property, the content, the other settings, and so on. Then, send your Notification through the notify () method.

Android3.0, create a notification directly before

1. Get the Notificationmanager Reference

Notificationmanager Mnotificationmanager = (notificationmanager) getsystemservice (Context. Notification_service);

2. Create Notification

Notification notification =newnotification(icon,tickertext,when);

3. Define the content and pendingintentof the notification:

// instantiation of Intent

Intent notificationintent = new Intent (This, MyClass. Class);

// Get pendingintent

Pendingintent contentintent =pendingintent.getactivity (This, 0,notificationintent, 0);

// Setting Event Information

Notification.setlatesteventinfo (Context,contenttitle, ContentText, contentintent);

4. Pass the Notification to notificationmanager:

Mnotificationmanager.notify(ID, notification);
After 3.0, in order to better manage notifications, ANDROIDSDK introduces notification's internal class Notification.builder, which is commonly used to manage notification, dynamically set some properties of notification, use set to set related properties, set method has return value, returns the configured The Builder object.

Notificationmanager Notificationmanager = (notificationmanager) getsystemservice (notification_service);

Builder Builder = new Notificationcompat. Builder (mainactivity. this);

pendingintent contentindent =pendingintent. getactivity (mainactivity. this, 0,newIntent(mainactivity. this,mainactivity. class),pendingintent. Flag_update_current);

Builder . Setcontentintent(contentindent)

. Setsmallicon (R.drawable.ic_launcher)// Set Small icons displayed in the status bar

. Setlargeicon (Bitmapfactory.decoderesource (RES,R.DRAWABLE.I5))// drop-down list icons (large icons)

. Setticker ("This is bitch!") // set the display information for the status bar  

. Setwhen (System.currenttimemillis ())// set time to occur

. Setautocancel (true)// set to clear

. Setcontenttitle ("This is Contenttitle")// set the title of the dropdown list

. Setcontenttext ("This is ContentText"); // Setting Context Content  

// gets a new property that adds a variety of properties . Notification Object

NotificationNotification = builder. Build ();

// Plus ID is to show more than one Notification

Notificationmanager.notify(id,notification);

★ The first parameter to send the notification method is the ID of the notification, and the second parameter is the Notification instance to send. ID is the notification in your program identification, update a notification is also through this ID, will not produce too much notification, as long as the ID is the same, you can update this notification.

★pendingintent and intent slightly different, it can set the number of executions, mainly for remote service communication, Alarm, notification, launcher, SMS. Notification supports multiple intent to respond to click events, eliminate events, handle full-screen events of critical state, and so on, using Setcontentintent (pendingintent Intent) to handle the above events.

Add sound, vibration and flash for notifications
Add sound

You can either set a default sound to the notification or specify a sound in the program.

Default sound: Notification.defaults |=notification.default_sound;

Custom notification sounds:

// get default ringtone

. SetDefaults (Notification.default_sound)

// get a custom ringtone  

. Setsound (Uri.parse ("File:///sdcard/xx/xx.mp3"))

// Get Android ringtones within the multimedia library  

. Setsound (Uri.withappendedpath (Audio.Media.INTERNAL_CONTENT_URI,"5"))

★ If there is default_soundin the Defaults property, the default sound will overwrite the custom settings.

Add Vibration

Users can be prompted by default vibrations, or a form of vibration may be customized in the app.

Use the default vibration:

Notification.defaults |= notification.default_vibrate;

To implement a custom vibration, pass a long array to the vibrate property:

Long [] vibrate ={0,100,200,300}; // Delay 0ms , Vibration 100ms , Delay 200ms , Vibration 300ms

Builder. Setvibrate (vibrate);

★ If the default_vibrate value is included in the Defaults property, the default vibration form will override the custom vibration

Add Flash

You can use the default flash, or you can customize the color and form of the flash in your program.

Use the default flash:

Notification.defaults |= notification.default_lights;
Custom Flash:

You need to set the following properties Ledargb to indicate the color,ledoffms to indicate the time of the light off,ledonms to indicate the time of light

Builder. setlights (int ARGB,int onms,int OFFMS)

★ Three-color lamp reminders are only supported when the flags are set to notification.flag_show_lights.

★ Color is related to the device, not all colors can be, to see the specific equipment.

Other flags and attribute fields and methods commonly used by notification

flag_auto_cancel : When the user clicks the notification, the notification will be automatically canceled.

flag_insistent: Notifies the audio that it will continue to play repeatedly until the user responds to the notification.

Flag_only_alert_once: Once the notification is launched, the ringtones and vibrations are performed only once

flag_ongoing_event: Categorized under "Running"

flag_no_clear: Clear notification does not clear the notification

Flag_foreground_service: Indicates a service that is running

How to use: Use flags to add the corresponding property value after the instantiation of the notification bar, using or representing multiple attributes

Notification Notification = mbuilder. Build ();

Notification. flags= Notification.flag_auto_cancel;

Number Records multiple notifications

SetDefaults (int defaults)

The simplest to add sound, strobe, and vibration effects to a notification, using the default (Defaults) property, you can combine multiple property properties:

Notification.default_vibrate//Add default vibrate reminder

Notification.default_sound//Add default sound alerts

notification.default_lights//Add a default tri-color light reminder

notification.default_all//Add a default of 3 full reminders

.setpriority (int pri)

Function: Set the priority level

The corresponding priority description is as follows:

MAX

TD valign= "Top" >

priority

user

Important and urgent notifications informing users that this event is time-critical or needs to be dealt with immediately.

High

Higher priority for important communication content, such as short messages or chats, which are more useful to users Interesting.

default

Default priority is used for notifications with no special priority classification.

Low

Lower priority can notify the user but is not a very urgent event.

MIN

For background messages (such as weather or location information). The lowest priority notification will only display the icon in the status bar, and only the user drop-down notification drawer can see the content.


Setongoing (booleanongoing)

Function: Set to Ture, which indicates that it is an in-progress notification. They are usually used to represent a background task and cannot be deleted

Customizing the layout of notifications

Use remoteviews to customize the display of notifications when there is a need to display non-default content in notifications

The custom layout of notification is remoteviews, just like other remoteviews, in a custom view layout file, only framelayout, LinearLayout, Relativelayout three layout controls and AnalogClock, Chronometer, Button, ImageButton, ImageView, ProgressBar, TextView, Viewflipper, ListView, GridView, StackView, and adapterviewflipper these display controls, which do not support subclasses of these classes or other controls provided by Android, cause classnotfoundexception exceptions

The steps are as follows:

1) Create a custom view

2) Get the Remote View object

remoteviews contentview = newremoteviews(Getpackagename (), R.layout. Custom_notification_layout);

Contentview.setimageviewresource (r.id.image,r.drawable.notification_image);

Contentview.settextviewtext (R.id.title,"customnotification");

Contentview.settextviewtext (R.id.text,"This is Acustom layout");

To pass the Removeviews object to the notification contentView property

Mbuilder.setcontent (Mremoteviews)

3) Set Pendingintent (to respond to various events)

Mremoteviews.setonclickpendingintent (R.id.btn_custom_prev,intent_prev);

4) Launch notification

Mnotificationmanager.notify(Notifyid, notify);

Android System Application---One of notification: Notification Overview and use

Related Article

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.