. Android notification Basics

Source: Internet
Author: User

When a user receives a call, a small icon appears in the top Status Bar of Android. The system prompts you whether there are any processed news. You can view these news when you drag the status bar. Android provides icationicationmanager to manage the status bar. It can be easily completed.

(Do you want to go to YouTube or Facebook? Do you know the latest international and domestic situations? Please mail to freeget.one@gmail.com for software)

To add a notification, follow these steps:

1: Obtain icationicationmanager:

Icationicationmanager m_notificationmanager = (notificationmanager) This. getsystemservice (icationication_service );

2: Define a notification:

Notification m_notification = new notification ();

3: set various attributes of notification:

// Set the icon of the notification displayed in the status bar
M_icationication.icon = R. drawable. Icon;

// Content displayed when we click the notification
M_icationication.tickertext = "button1 notification content .....";

Default sound sent during notification
M_icationication.defaults = notification. default_sound;

// Set the notification display parameters

Intent m_intent = new intent (icationicationdemo. This, desactivity. Class );
Pendingintent m_pendingintent = pendingintent. getactivity (icationicationdemo. This, 0, m_intent, 0 );

M_icationication.setlatesteventinfo (icationicationdemo. This, "button1", "button1 notification", m_pendingintent );

// This can be understood as starting to execute this notification
M_icationicationmanager.policy (0, m_notification );

4: Now that you can add or delete it. Of course, it is just to delete what you add.

M_icationicationmanager.cancel (0 );

Here 0 is an ID number, which is the same as the first parameter 0 of policy.

This completes adding and deleting.

Here we use a demo to conceal our operations.

1: Create a project icationicationdemo.

2: add an activity: desactivity. Note that you must declare it in manifest. xml.

3: The laytout file in icationicationdemo is a simple definition of a button. The code file is as follows:

View plaincopy to clipboardprint?
Package com. Rocky. Studio. ch4221;
Import Android. App. activity;
Import Android. App. notification;
Import Android. App. icationicationmanager;
Import Android. App. pendingintent;
Import Android. content. intent;
Import Android. OS. Bundle;
Import Android. View. view;
Import Android. widget. Button;
Import Android. widget. textview;
Public class icationicationdemo extends activity {

Button m_button1;
Textview m_txtview;

Icationicationmanager m_notificationmanager;
Notification m_notification;

Intent m_intent;
Pendingintent m_pendingintent;

/** Called when the activity is first created .*/
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );

M_icationicationmanager = (notificationmanager) This. getsystemservice (icationication_service );



M_button1 = (button) This. findviewbyid (R. Id. button01 );


// Transfer content when you click the notification
M_intent = new intent (icationicationdemo. This, desactivity. Class );

M_pendingintent = pendingintent. getactivity (icationicationdemo. This, 0, m_intent, 0 );


M_notification = new notification ();

M_button1.setonclicklistener (New button. onclicklistener (){
Public void onclick (view v ){
// Todo auto-generated method stub

// Set the icon of the notification displayed in the status bar
M_icationication.icon = R. drawable. Icon;

// Content displayed when we click the notification
M_icationication.tickertext = "button1 notification content .....";

// Default sound sent during notification
M_icationication.defaults = notification. default_sound;

// Set the notification display parameters
M_icationication.setlatesteventinfo (icationicationdemo. This, "button1", "button1 notification", m_pendingintent );


// This can be understood as starting to execute this notification
M_icationicationmanager.policy (0, m_notification );

}});

}


}
Package com. Rocky. Studio. ch4221;
Import Android. App. activity;
Import Android. App. notification;
Import Android. App. icationicationmanager;
Import Android. App. pendingintent;
Import Android. content. intent;
Import Android. OS. Bundle;
Import Android. View. view;
Import Android. widget. Button;
Import Android. widget. textview;
Public class icationicationdemo extends activity {
 
Button m_button1;
Textview m_txtview;
 
Icationicationmanager m_notificationmanager;
Notification m_notification;
 
Intent m_intent;
Pendingintent m_pendingintent;

/** Called when the activity is first created .*/
@ Override
Public void oncreate (bundle savedinstancestate ){
Super. oncreate (savedinstancestate );
Setcontentview (R. layout. Main );

M_icationicationmanager = (notificationmanager) This. getsystemservice (icationication_service );


M_button1 = (button) This. findviewbyid (R. Id. button01 );


// Transfer content when you click the notification
M_intent = new intent (icationicationdemo. This, desactivity. Class );

M_pendingintent = pendingintent. getactivity (icationicationdemo. This, 0, m_intent, 0 );

M_notification = new notification ();

M_button1.setonclicklistener (New button. onclicklistener (){
Public void onclick (view v ){
// Todo auto-generated method stub

// Set the icon of the notification displayed in the status bar
M_icationication.icon = R. drawable. Icon;

// Content displayed when we click the notification
M_icationication.tickertext = "button1 notification content .....";

// Default sound sent during notification
M_icationication.defaults = notification. default_sound;

// Set the notification display parameters
M_icationication.setlatesteventinfo (icationicationdemo. This, "button1", "button1 notification", m_pendingintent );

// This can be understood as starting to execute this notification
M_icationicationmanager.policy (0, m_notification );

}});

}


}

4: Modify the source file of desactivity. The Code is as follows:

View plaincopy to clipboardprint?
01. Package com. Rocky. Studio. ch4221;
02. Import Android. App. activity;
03. Import Android. App. icationicationmanager;
04. Import Android. OS. Bundle;
05. Public class desactivity extends activity {
06.
07. icationicationmanager m_notificationmanager;
08.
09. @ override
10. Protected void oncreate (bundle savedinstancestate ){
11. // todo auto-generated method stub
12. Super. oncreate (savedinstancestate );
13. This. setcontentview (R. layout. main2 );
14.
15. // Delete the previously defined
16. m_icationicationmanager = (notificationmanager) This. getsystemservice (icationication_service );

17. m_icationicationmanager.cancel (0 );
18 .}
19.
20 .}
Package com. Rocky. Studio. ch4221;
Import Android. App. activity;
Import Android. App. icationicationmanager;
Import Android. OS. Bundle;
Public class desactivity extends activity {
 
Icationicationmanager m_notificationmanager;
 
@ Override
Protected void oncreate (bundle savedinstancestate ){
// Todo auto-generated method stub
Super. oncreate (savedinstancestate );
This. setcontentview (R. layout. main2 );

// Delete the previously defined
M_icationicationmanager = (notificationmanager) This. getsystemservice (icationication_service );
M_icationicationmanager.cancel (0 );
}
 
}
 

The Code is also very simple. You can view the notification and notificationmananger classes to learn about them.

The following is an article that describes the notification and icationicationmanager classes in detail.

Noticificationmanager can be easily placed in the status bar, and it is easy to access the program from statusbar,
In noticificationmanager, you can use intent to execute the activity of this program.

Noticificationmanager status bar operation

Icationicationmanager (Notification manager ):
Icationicationmanager is responsible for notifying users of events.
Icationicationmanager has three common methods:
1. Cancel (int id) cancels a previously displayed notification. If it is a short notification, it tries to hide it. If it is a persistent notification, it will be removed from the status bar.
2. cancelall () cancels all previously displayed notifications.
3. Y (int id, Notification) permanently sends the notification to the status bar.

// Initialize icationicationmanager:
Icationicationmanager Nm =
(Icationicationmanager) getsystemservice (notification_service );

Notification indicates a notification.
Notification attributes:
Audiostreamtype the type of the audio stream used when the sound starts
When a notification entry is clicked, contentintent executes the configured intent.
Contentview: When a notification is displayed on the status bar, the configured view is also displayed.
Defaults specifies the value to be set to the default value.
Deleteintent when you click the "Clear all notifications" button to delete all notifications, the configured intent is executed.
The image used by the icon status bar.
Iconlevel if there are several levels of Status Bar images, set it here.
Ledargb LED light color.
Flash time when ledoffms LED is disabled (in milliseconds)
Flash time when ledonms led starts (in milliseconds)
Number indicates the number of the event.
Sound notification sound
Information displayed when the tickertext notification is displayed in the status bar
Vibrate vibration mode.
The timestamp of the when notification.

Send notification to status bar:
Notification = new notification ();
Notification setting process ........
Nm. Y (0, notification); // it is sent to the status bar.

Create and trigger notification

Three steps are required to create and configure a new notification.

First, you need to create a new notification object and pass in the current time of the graph label, text, and notification to be displayed on the status bar, as shown in the following code snippet:

// Choose a drawable to display as the status bar icon
Int icon = R. drawable. Icon;

// Text to display in the status bar when the notification is launched
String tickertext = "notification ";

// The extended status bar orders notification in time order
Long when = system. currenttimemillis ();
Notification = new notification (icon, tickertext, when );

When notification is triggered, the text will scroll along the status bar.

Second, use the setlatesteventinfo method to configure the appearance of notification in the extended status window. The extended status window displays the icon, the time passed in the constructor, the title, and a detailed string. Notification generally indicates a request for an action or attracts the user's attention. Therefore, you can specify a pendingintent to trigger the notification when the user clicks the notification item.


The following code snippet uses setlastesteventinfo to set these values:

Context context = getapplicationcontext ();

// Text to display in the extended status window
String expandedtext = "extended status text ";

// Title for the expanded status
String expandedtitle = "Notification title ";

// Intent to launch an activity when the Extended text is clicked
Intent intent = new intent (this, myactivity. Class );
Pendingintent launchintent = pendingintent. getactivity (context, 0, intent, 0 );
Notification. setlatesteventinfo (context,
Expandedtitle,
Expandedtext,
Launchintent );

A good form is to use a notification icon when displaying multiple objects of the same event (for example, receiving multiple SMS messages. To present to users, use setlastesteventinfo to update the dataset to present the most recent message and re-trigger notification to update its value.


You can also use the number attribute to display the number of events represented by a status bar icon.

Set to a value greater than 1, as shown in the following figure. A small number is displayed on the status bar icon:

Notification. Number ++;

You must re-trigger any changes to the notification to update the notification. If you want to delete this number, set the value of number to 0 or-1.

Finally, you can use multiple attributes for notification objects to enhance the notification effect, such as flashing LEDs, vibrating phones, and playing music files. These advanced features are described in detail later in this chapter.


Trigger notification

To trigger a notification, use icationicationmanager's notify y method to pass in an integer ID and notification object, as shown in the following snippet:


Int notificationref = 1;
Icationicationmanager. Notify (notificationref, notification );

To update a triggered notification, the same ID is passed in. You can either pass in the same notification object or be a brand new object. Only the IDS must be the same. The new notification object replaces the status bar.

Icon and extended status window details.

You can also use ID to cancel notification by calling the Cancel Method of icationicationmanager, as shown below:

Icationicationmanager. Cancel (notificationref );

When a notification is canceled, its status bar icon is removed and its information in the extended status window is cleared.

Basic usage of notification and icationicationmanager

1. icationicationmanager and notification are used to set notifications.

The notification setting and other operations are relatively simple. The basic method is to create a notification object and set the notification parameters, then, use the icationicationmanager service running in the system background to send the notification.

The basic steps are as follows:

1) Obtain icationicationmanager:

String NS = context. icationication_service;

Icationicationmanager mnotificationmanager = (notificationmanager) getsystemservice (NS );

 

2) create a new notification object:

Notification = new notification ();

Notification. Icon = R. drawable. icationication_icon;

 

You can also create a notification in a slightly more complex way:

Int icon = R. drawable. icationication_icon; // notification icon

Charsequence tickertext = "hello"; // notification text prompt displayed in the status bar

Long when = system. currenttimemillis (); // the time when a notification is generated. It is displayed in the notification information.

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

 

3) Fill in the attributes of notification:

Context context = getapplicationcontext ();

Charsequence contenttitle = "my notification ";

Charsequence contenttext = "Hello world! ";

Intent icationicationintent = new intent (this, myclass. Class );

Pendingintent contentintent = pendingintent. getactivity (this, 0, icationicationintent, 0 );

Notification. setlatesteventinfo (context, contenttitle, contenttext, contentintent );

 

Notification provides a wide range of mobile phone prompts:

A) notification text prompts displayed in the status bar, such:

Notification. tickertext = "hello ";

 

B) make a prompt, for example:

Notification. defaults | = notification. default_sound;

Notification. Sound = URI. parse ("file: // sdcard/notification/ringer.pdf ");

Notification. Sound = URI. withappendedpath (audio. Media. internal_content_uri, "6 ");

 

C) Mobile Phone vibration, such:

Notification. defaults | = notification. default_vibrate;

Long [] vibrate = {0,100,200,300 };

Notification. vibrate = vibrate;

 

D) LED light flashes, such:

Notification. defaults | = notification. default_lights;

Notification. ledargb = 0xff00ff00;

Notification. ledonms = 300;

Notification. ledoffms = 1000;

Notification. Flags | = notification. flag_show_lights;

 

4) send notifications:

Private Static final int id_notification = 1;

Micationicationmanager. Y (id_notification, notification );

 

2. update notifications

To update a notification, you only need to call setlatesteventinfo after setting the notification, and then re-send the notification.

 

NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

In the above sentence, getsystemservice () is used to obtain the system service from the system.

 

Notification notification = new Notification(R.drawable.notiicon, msg.getTitle(), System.currentTimeMillis());notification.flags = Notification.FLAG_AUTO_CANCEL;

 

Then, a notification is constructed, which includes three attributes, icons, text behind the icon, and the time displayed in the notification time section. The current time is usually used. Flag_auto_cancel indicates that the notification disappears after one click.

 

Intent intent = new Intent(this, MainActivity.class);Bundle bundle = new Bundle();bundle.putString("info", msg.getInfo());intent.putExtras(bundle);intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_NEW_TASK);

 

The code above constructs an intent and adds a piece of information. Flag_activity_clear_top, flag_activity_new_task two flags indicate that the application already opened is preferred. If the application is not opened, start it.

 

PendingIntent contentIntent = PendingIntent.getActivity(this, id,intent, PendingIntent.FLAG_UPDATE_CURRENT);

This code wraps intent in pendingintent. This is context, and ID is the identifier of pendingintent. If the ID is the same, it is considered as one. Flag_update_current indicates that the pendingintent will be updated later.

 

notification.setLatestEventInfo(this, msg.getTitle(), msg.getInfo(),contentIntent);notiManager.notify(id, notification);

The last two rows Add the status bar details, wrap pendingintent to notification, and finally send 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.