Android Learning 13 (Android notifications are used)

Source: Internet
Author: User

notification (Notification) is a feature that is featured in the Android system, and can be implemented with notifications when an application wants to send a message to the user that the application is not running in the foreground. When a notification is issued, the status bar at the top of the phone displays an icon for the notification, and the drop-down status allows you to see the details of the notification.


Basic usage of notifications

Notifications can be created in activities, broadcast receivers, and services. No matter where you create the notification, the overall steps are the same, let's learn the detailed steps below.

/* * First requires a notificationmanager to manage notifications, which can be obtained by invoking the Getsystemservice () method of the context. The Getsystemservice method receives a string parameter to determine which service to get the system, and here we pass in the * context.notification_service. So get an example of Notificationmanager, which can be written as: * Notificationmanager manager= (Notificationmanager) Getsystemservice ( Context.notification_service); * Next, create a notification object, which is used to store the various information required by the notification, and we use its constructor to create it. * Notification has a parameter constructor to receive three parameters, the first parameter is used to specify the icon of the notification, such as the project's res/drawable directory * under a ic_launcher picture, then here can be passed R.DRAWABLE.IC_ Launcher, the second parameter is used to specify the ticker content of the notification *, when the notification has just been created, it will flash in the status bar of the system, which is a momentary hint of information. The third parameter is used to specify when the notification is created, in milliseconds, when the system status bar is pulled, and the time specified here is displayed on the corresponding notification. So create * A Notification object can be written as: * Notification notification=new Notification (R.drawable.ic_launcher, "This is ticker text" , System.currenttimemillis ()); * Once the notification object has been created, we also need to set the layout of the notification, where only the call to notification * The Setlatesteventinfo () method allows you to set a standard layout for the notification. This method receives four parameters, the first parameter * is the context. The second parameter is used to specify the title of the notification, and the drop-down system status bar is where you can see the content. The third parameter is used to specify the body content of the notification, which can be seen in the same drop-down system status bar. The fourth parameter we do not use temporarily, can pass null. So * Set the layout of the notification can be written as: * notification.setlatesteventInfo (This, "This is the content title", "This is content text", null);  After the above work is done, only call Notificationmanager's Notify () method to let the notification appear. The Notify () method receives 2 parameters, the first parameter is the ID, and the ID that is specified for each notification is different. The second parameter is the notification object, which directly passes in the notification object we just created. Therefore, the display of a notification can be written as: Manager.notify (1,notification); * */

Create a new project with the project name Notificationtest and modify the code in the Activity_main.xml as follows:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:orientation= "vertical"    >    <button         android:id= "@+id/send_notice"        android: Layout_width= "Match_parent"        android:layout_height= "wrap_content"        android:text= "send notice"        /> </LinearLayout>

To modify the code in Mainactivity:

Package Com.jack.notificationtest;import Android.os.bundle;import Android.app.activity;import Android.app.notification;import Android.app.notificationmanager;import Android.content.context;import Android.content.intentsender.sendintentexception;import Android.view.menu;import Android.view.View;import Android.view.view.onclicklistener;import Android.widget.button;public class Mainactivity extends Activity implements onclicklistener{/* * First requires a notificationmanager to manage notifications, which can be obtained by invoking the Getsystemservice () method of the context. The Getsystemservice method receives a string parameter to determine which service to get the system, and here we pass in the * context.notification_service. So get an example of Notificationmanager, which can be written as: * Notificationmanager manager= (Notificationmanager) Getsystemservice ( Context.notification_service); * Next, create a notification object, which is used to store the various information required by the notification, and we use its constructor to create it. * Notification has a parameter constructor to receive three parameters, the first parameter is used to specify the icon of the notification, such as the project's res/drawable directory * under a ic_launcher picture, then here can be passed R.DRAWABLE.IC_ Launcher, the second parameter is used to specify the ticker content of the notification *, when the notification has just been created, it will flash in the status bar of the system, which is a momentary hint of information. The third parameter is used to specify when the notification is created, in milliseconds, when the system status bar is pulled,The time specified here is displayed on the appropriate notification. So create * A Notification object can be written as: * Notification notification=new Notification (R.drawable.ic_launcher, "This is ticker text" , System.currenttimemillis ()); * Once the notification object has been created, we also need to set the layout of the notification, where only the call to notification * The Setlatesteventinfo () method allows you to set a standard layout for the notification. This method receives four parameters, the first parameter * is the context. The second parameter is used to specify the title of the notification, and the drop-down system status bar is where you can see the content. The third parameter is used to specify the body content of the notification, which can be seen in the same drop-down system status bar. The fourth parameter we do not use temporarily, can pass null.  therefore * the layout of the notification can be written as follows: * Notification.setlatesteventinfo (this, "the" content title "," This is content text ", null);  After the above work is done, only call Notificationmanager's Notify () method to let the notification appear. The Notify () method receives 2 parameters, the first parameter is the ID, and the ID that is specified for each notification is different. The second parameter is the notification object, which directly passes in the notification object we just created. Therefore, the display of a notification can be written as: Manager.notify (1,notification); * */private Button sendnotice; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); SendNotice= ( Button) Findviewbyid (R.id.send_notice); Sendnotice.setonclicklistener (this);} @Overridepublic Boolean OncreateopTionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R. Menu.main, menu); return true;} @Overridepublic void OnClick (View v) {//TODO auto-generated method Stubswitch (V.getid ()) {case R.id.send_notice: Notificationmanager manager= (Notificationmanager) Getsystemservice (Context.notification_service); Notification notification=new Notification (R.drawable.ic_launcher, "This is ticker text", System.currenttimemillis ()) ; Notification.setlatesteventinfo (This, "This is the content title", "This is content text", null); Manager.notify (1, notification); break;default:break;}}}

To run the program, click on the notice interface as follows:



The drop-down system status bar can see the details of the notification as follows:



Above the notice, we can not click, if you want to achieve the click effect of the notification, we will be in the code to set the corresponding, which involves the pendingintent. Pendingintent and intent are somewhat similar, and they do exist in a number of similarities. They can, for example, specify an "intent" that can be used to initiate activities, start services, and send broadcasts. The difference is that intent is more inclined to perform an action at once, while Pendingintent prefers to perform an action at a suitable time. Therefore, pendingintent can be simply understood as the intent of deferred execution.

    The use of the pendingintent is relatively simple, and it provides several static methods for obtaining pendingintent instances, you can choose whether to use the Getactivity () method, the Getbroadcast () method, or the GetService () method, depending on your needs. The parameters received by these methods are the same, and the first parameter is still the context. The second parameter is generally not available, usually passing in a 0. The third parameter is a intent object, which allows us to construct pendingintent "intent". The fourth parameter is used to determine the behavior of the pendingintent, with Flag_one_shot,flag_no_create,flag_cancel _current and  flag_update_current These four kinds of values are optional, the meaning of each value, you can query under their own.

< Span style= "font-size:17.7777786254883px" >    Remember notification's Setlatesteventinfo () method. Just now we will setlatesteventinfo () the fourth parameter ignored, directly passed to NULL, you will find that the fourth parameter is exactly a pendingintent object. Thus, it is possible to construct a deferred execution "intent" by pendingintent, which executes the logic when the user clicks on the notification.

< Span style= "font-size:17.7777786254883px" >< Span style= "font-size:17.7777786254883px" >    Now let's optimize the next notificationtest project, add the click function to the notification just Let the user click on it to start another activity.

< Span style= "font-size:17.7777786254883px" >< Span style= "font-size:17.7777786254883px" >    first need to prepare an activity, here the new layout file Notification_layout.xml, the code is as follows:

< Span style= "font-size:17.7777786254883px" >< Span style= "font-size:17.7777786254883px" >

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "vertical" >        <textview         android:layout_width= "wrap_content"        android:layout_height= " Wrap_content "        android:textsize=" 24sp "        android:text=" This is Notificaiton layout "        /></ Linearlayout>


The new Notificationactivity class inherits the activity, loading the layout defined above, as shown in the following code:

Package Com.jack.notificationtest;import Android.app.activity;import Android.os.bundle;public class Notificationactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {//TODO Auto-generated method Stubsuper.oncreate (savedinstancestate); Setcontentview (r.layout.notification_layout);}}
Modify the code in the Androidmanifest.xml to include the Notificationactivity registration statement:

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.jack.notificationtest "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-s DK android:minsdkversion= "android:targetsdkversion="/> <application Android:allowbac Kup= "true" android:icon= "@drawable/ic_launcher" android:label= "@string/app_name" Android:theme= "@styl E/apptheme "> <activity android:name=" com.jack.notificationtest.MainActivity "android:l Abel= "@string/app_name" > <intent-filter> <action android:name= "Android.intent.actio N.main "/> <category android:name=" Android.intent.category.LAUNCHER "/> </intent-fil ter> </activity> <activity android:name= "Com.jack.notificationtest.Notificat Ionactivity "></activiTy> </application></manifest> 

The following changes the code in the mainactivity to give the notification to join the Click function as follows:

@Overridepublic void OnClick (View v) {//TODO auto-generated method Stubswitch (V.getid ()) {case R.id.send_notice: Notificationmanager manager= (Notificationmanager) Getsystemservice (Context.notification_service); Notification notification=new Notification (R.drawable.ic_launcher, "This is ticker text", System.currenttimemillis ()) ; Intent intent=new Intent (this,notificationactivity.class); Pendingintent pi=pendingintent.getactivity (This, 0,intent, pendingintent.flag_cancel_current); Notification.setlatesteventinfo (This, "This is the content title", "This is content text", pi); manager.notify (1, notification); break;default:break;}}


Re-run the next program, and click the Send Notice button, will still send a notification, let back down the system status bar, click on the notification, you will see the notificationactivity this activity interface. As shown below:





Note that you will find that the icon on the system status has not disappeared, why is it? This is because if we do not cancel the notification in the code, it will always be displayed on the system's status bar. The solution is also relatively simple, call Notificationmanager's Cancel () method to cancel the notification. Modify the code in the notificationactivity as follows:


Package Com.jack.notificationtest;import Android.app.activity;import Android.app.notificationmanager;import Android.content.context;import Android.os.bundle;public class Notificationactivity extends Activity {@ overrideprotected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated method Stubsuper.oncreate ( Savedinstancestate); Setcontentview (r.layout.notification_layout); Notificationmanager manager= (Notificationmanager) Getsystemservice (Context.notification_service); Manager.cancel ( 1)/* * We have passed 1 in the Cancel () method, what does this 1 mean? This is the ID that we set for this notification is 1. * So if you want to cancel a notification, just pass in the ID of the notification in the Cancel () method. * */}}


Advanced Tips for Notifications

Observing notification This class, you will find that we still have a lot of attributes that are not used. Let's take a look at the sound of this property, which can broadcast a piece of audio at the time of notification, so that you can better inform the user that a notification is coming. Sound This property is a URI object, so you need to get the corresponding URI for the audio file when you specify the audio file. For example, there is a Basic_tone.ogg audio file in the/system/media/audio/ringtongs directory of the phone, so you can specify this in the code:

Uri Sounduri=uri.parse (New File ("/system/media/audio/ringtongs/basic_tone.ogg"));

Notification.sound=sounduri;

In addition to allowing audio playback, we can also make the phone vibrate when the notification arrives, using the vibrate property. It is a long-shaped array, in milliseconds, due to the length of time it takes to set the phone to rest and vibrate. The value of subscript 0 indicates the length of the phone at rest, the value of subscript 1 indicates the length of time the phone vibrates, and the value of 2 indicates the length of the phone at rest, and so on. So, if you want your phone to vibrate for 1 seconds at the time of notification, then at rest for 1 seconds, the code can be written as:

Long[] vibrates={0,1000,1000,1000};

Notification.vibrate=vibrates;


But to control the phone shake also need to declare permissions, therefore, we also have to edit the Androidmanifest.xml file, add the following instructions:

<uses-permission android.name= "Android.permission.VIBRATE"/>


Learn to control the sound and vibration of notifications, and let's look at how to control the display of your phone's LED lights when notifications arrive.

Now the phone is basically pre-set a LED light, when there are missed calls or unread text messages, and at this time the phone is in the lock screen state when the LED lights will continue to blink, remind users to check. We can use the LEDARGB,LEDONMS,LEDOFFMS and flags to achieve this effect. Ledargb is used to control the color of LED lights, generally with red, green and blue colors are optional. The LEDONMS is used to specify the length of time, in milliseconds, that the LED light is lit. Edoffms is also measured in milliseconds due to the length of time the LED light is dimmed. Flags can be used to specify some of the behavior of the notification, including the option to display an LED light. So, when the notification arrives, if you want to achieve the LED lights with green lights flashing a flash of the effect, you can write:

Notification.ledargb=color.green;

notification.ledonms=1000;

notification.ledoffms=1000;

Notification.flags=notification.flag_show_lights;

Of course, if you do not want to do so many cumbersome settings, you can also use the default effect of the notification, it will be based on the current phone's environment to decide what ringtone to play, and how to vibrate, as follows:

Notification.defaults=notification.default_all;

Note: The above-mentioned advanced techniques are to be run on the real machine, in order to see the effect, the simulator can not show vibration, and LED lights flashing and other functions.

Notice to summarize the amount, the following will be a text message to receive and send a summary.

Reprint Please specify: http://blog.csdn.net/j903829182/article/details/41181277


Android Learning 13 (Android notifications are used)

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.