Android development Notification

Source: Internet
Author: User

Notification usage --- status bar Notification


Two classes are required to send a status bar notification:

1. icationicationmanager --- the management class of status bar notifications, responsible for sending notifications, clearing notifications, etc.
Icationicationmanager: a system Service, which must be obtained through the context. getSystemService (NOTIFICATION_SERVICE) method.
Icationicationmanager NotificationManager = (notificationManager) context. getSystemService (android. content. Context. icationication_service );


2. Notification --- the specific status bar Notification object. You can set parameters such as icon, text, prompt sound, and vibration.
Below are the basic parameters required for setting a notification
Anicon (Notification icon)
Atitleanexpandedmessage (Notification title and content)
APendingIntent (click to jump to the notification execution page)

1. Create Notification
Use icationicationmanager's notify (int Id, Notification) method to start Notification
Parameter 1: Unique Identifier of Notification
Parameter 2: Notification object

2. Update Notification
Call the setLatestEventInfo () method of Notification to update the content, and then call icationicationmanager's notify () method.

3. Delete Notification
Use the cancle (int id) method of icationicationmanager to clear the Notification parameter: the unique identifier of the Notification to be cleared.

4. Notification Settings-vibration, ringtones, etc.

1. Basic settings:

// Create a new status bar Notification baseNF = new Notification (); // set the icon baseNF of the Notification displayed in the status bar. icon = R. drawable. icon; // The baseNF content displayed in the status bar during notification. tickerText = "YouclickedBaseNF! "; // Default notification parameters: DEFAULT_SOUND, DEFAULT_VIBRATE, and DEFAULT_LIGHTS. // if you want to use all the default values, use DEFAULT_ALL. // The default baseNF is used here. defaults = Notification. DEFAULT_SOUND; // The second parameter: the message title expandedmessagetitle displayed in the drop-down status bar // The third parameter: the message content expandedmessagetext displayed in the drop-down status bar // The fourth parameter: when you click this notification, the execution page jumps to baseNF. setLatestEventInfo (Lesson_10.this, "Title01", "Content01", pd); // send a status bar notification // ThefirstparameteristheuniqueIDfortheNotification // andthesecondisthenotificationicationobject. nm. Y (icationication_id_base, baseNF );

2. Add sound

BaseNF. default = Notification. DEFAULT_SOUND; -- use the system default prompt.

Notification. sound = Uri. parse ("file: // sdcard/notification/ringer.pdf"); --- custom sound

You can use the built-in ringtones as follows:

Notification. sound = Uri. withAppendedPath (Audio. Media. INTERNAL_CONTENT_URI, "6 ");

3. Add Vibration

Notification. defaults | = Notification. DEFAULT_VIBRATE; use the default Vibration Mode

4. Add flashing

Notification. defaults | = Notification. DEFAULT_LIGHTS;

5. other useful settings:

Flags: Notification. FLAG_INSISTENT; // infinite loop of sound and vibration until the user responds to Notification. FLAG_AUTO_CANCEL; // The Notification disappears automatically after the Notification is clicked. FLAG_NO_CLEAR; // when you click 'clear', the notification is not Clear (QQ notifications cannot be cleared, that is, this // custom drop-down view is used, such as when downloading software, the progress bar. Icationicationnotification = newNotification (); notification. icon = R. drawable. icon; notification. tickerText = "Custom! "; RemoteViewscontentView = newRemoteViews (getPackageName (), R. layout. custom); contentView. setImageViewResource (R. id. image, R. drawable. icon); contentView. setTextViewText (R. id. text, "Hello, thismessageisinacustompandedview"); notification. contentView = contentView; // when using a custom drop-down view, you do not need to call the setLatestEventInfo () method // but you must define the contentIntent notification. contentIntent = pd; nm. Y (3, notification );

Application Example 1:

According to the lifecycle of the activity, when the activity is not displayed, the onStop function (such as pressing the home Key) will be executed. Therefore, you put the notification in the notification bar in the onStop function (except press the return key, remove the notification from the notification bar. Or, the notification bar icon is displayed as long as the program is running. The following describes some constants and fields in the Notification class. constants: DEFAULT_ALL use all default values, such as sound, vibration, flash screen, etc. DEFAULT_LIGHTS use the default flash prompt DEFAULT_SOUNDS use the default prompt sound DEFAULT_VIBRATE use the default phone shake [note]: add the phone shake, must be in manifest. add permissions to xml:
 The above effect constants can be superimposed through notification. defaults = DEFAULT_SOUND | DEFAULT_VIBRATE; notification. defaults | = DEFAULT_SOUND (it is best to test it on a real machine, not on a simulator) // set flag FLAG_AUTO_CANCEL to clear FLAG_NO_CLEAR from the status bar. The FLAG_ONGOING_EVENT will be cleared from the FLAG_INSISTENT status bar. Will the FLAG_INSISTENT remain running, for example, if you want to keep playing the music and know the common field of user response: contentIntent sets the PendingIntent object, send the Intentdefaults to add the default effect flags to set the flag bit when you click it, for example, FLAG_NO_CLEAR, etc. icon set, sound set, text displayed in the status bar, tickerText, And the timestamp when the notification is sent. icationicationmanager common method: public void cancelAll () remove all notifications (only for notifications under the current Context) public void cancel (int id) Remove notifications marked as IDS (only for all notifications under the current Context) public void y (String tag, int id, Notification notification) adds the Notification to the status bar. The tag is the tag and the tag is idpublic void notify (int id, notification Notification, mark as idpackage com. ljq. activity; import android. app. activity; import android. app. notification; import android. app. icationicationmanager; import android. app. pendingIntent; import android. content. intent; import android. graphics. color; import android. OS. bundle; public class MainActivity extends Activity {/** Called when the activity is first created. * // @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); clearNotification () ;}@ Override protected void onStop () {showNotification (); super. onStop () ;}@ Override protected void onStart () {clearNotification (); super. onStart ();}/*** display notification in the status bar */private void showNotification () {// create a icationicationmanager reference icationicationmanager = (icationicationmanager) this. getSystemService (android. content. context. NOTIFICATION_SERVICE); // defines the attributes of Notification. Notification notification = new Notification (R. drawable. icon, "Supervisor System", System. currentTimeMillis ()); // FLAG_AUTO_CANCEL: This notification can be cleared by the clear button of the status bar. // FLAG_NO_CLEAR: This notification cannot be cleared by the clear button of the status bar. // FLAG_ONGOING_EVENT: the notification is being run. // FLAG_INSISTENT:, for example, the music is always played and the user knows to respond to notification. flags | = Notification. FLAG_ONGOING_EVENT; // place the notification in the notification bar, that is, notification in the running group. flags | = Notification. FLAG_NO_CLEAR; // indicates that the notification is not cleared after you click "clear notification" in the notification bar. The notification is often used with FLAG_ONGOING_EVENT. flags | = Notification. FLAG_SHOW_LIGHTS; // DEFAULT_ALL use all default values, such as sound, vibration, and pop-up. // DEFAULT_LIGHTS use the default flash prompt // DEFAULT_SOUNDS use the default prompt sound // DEFAULT_VIBRATE use the default phone shake, add
 Permission notification. defaults = Notification. DEFAULT_LIGHTS; // constant of the superposition effect // notification. defaults = Notification. DEFAULT_LIGHTS | Notification. DEFAULT_SOUND; notification. ledARGB = Color. BLUE; notification. ledOnMS = 5000; // flash time, millisecond // set the notification event message CharSequence contentTitle = "Supervisor System title"; // notification bar title CharSequence contentText = "Supervisor System content "; // Intent notificationIntent = new Intent (MainActivity. this, MainActivity. class );/ /Click the Activity PendingIntent contentItent = PendingIntent to jump to after the notification. getActivity (this, 0, icationicationintent, 0); notification. setLatestEventInfo (this, contentTitle, contentText, contentItent); // transmits the Notification to icationicationmanager. Y (0, notification );}? // Delete notification private void clearNotification () {// Delete the notification NotificationManager defined previously (notificationManager) this. getSystemService (icationication_service); icationicationmanager. cancel (0 );}}

Application Example 2:

When we use a mobile phone, if we receive a text message without clicking to view it, is there a small text message icon prompt in the top status bar of the mobile phone? Do you also want to implement this function? Today's Notification solves this problem.

[Java]View plaincopy
  1. Package cn.com. chenzheng_java;
  2. Import android. app. Activity;
  3. Import android. app. Notification;
  4. Import android. app. icationicationmanager;
  5. Import android. app. PendingIntent;
  6. Import android. content. Context;
  7. Import android. content. Intent;
  8. Import android.net. Uri;
  9. Import android. OS. Bundle;
  10. Import android. provider. MediaStore. Audio;
  11. Import android. view. View;
  12. Import android. widget. Button;
  13. /***
  14. * @ Description status bar notifications
  15. * @ Author chenzheng_java
  16. *
  17. */
  18. Public class icationicationactivity extends Activity {
  19. @ Override
  20. Protected void onCreate (Bundle savedInstanceState ){
  21. Super. onCreate (savedInstanceState );
  22. SetContentView (R. layout. notification );
  23. Button button = (Button) findViewById (R. id. button );
  24. Button. setOnClickListener (new View. OnClickListener (){
  25. @ Override
  26. Public void onClick (View v ){
  27. AddNotificaction ();
  28. }
  29. });
  30. }
  31. /**
  32. * Add a notification
  33. */
  34. Private void addNotificaction (){
  35. Icationicationmanager manager = (NotificationManager) this
  36. . GetSystemService (Context. icationication_service );
  37. // Create a Notification
  38. Notification notification = new Notification ();
  39. // Set the icon of the status bar at the top of the mobile phone
  40. Notification. icon = R. drawable. excel;
  41. // When the current notification is placed on the status bar, the message is displayed.
  42. Notification. tickerText = "Note: I 've been thrown to the status bar ";
  43. /***
  44. * Notification. contentIntent: A PendingIntent object. When a user clicks the icon on the status bar, the Intent will be triggered.
  45. * Notification. contentView: we can put a view instead of the icon in the status bar.
  46. * Notification. deleteIntent: intent executed when the current notification is removed
  47. * Notification. vibrate: sets the vibration cycle when the mobile phone shakes.
  48. */
  49. // Add a sound prompt
  50. Notification. defaults = Notification. DEFAULT_SOUND;
  51. // The audioStreamType value must be the value in AudioManager, representing the ringing mode.
  52. Notification. audioStreamType = android. media. AudioManager. ADJUST_LOWER;
  53. // You can add music in the following two ways
  54. // Notification. sound = Uri. parse ("file: // sdcard/notification/ringer.pdf ");
  55. // Notification. sound = Uri. withAppendedPath (Audio. Media. INTERNAL_CONTENT_URI, "6 ");
  56. Intent intent = new Intent (this, Notification2Activity. class );
  57. PendingIntent pendingIntent = PendingIntent. getActivity (this, 0, intent, PendingIntent. FLAG_ONE_SHOT );
  58. // Click the icon in the status bar to set the prompt information
  59. Notification. setLatestEventInfo (this, "content prompt:", "I am a test file", pendingIntent );
  60. Manager. Y (1, notification );
  61. }
  62. }

    When you click the button, the status bar displays:

    VcHLsMmjrNe0zKzAuLbgs/routing + CjxpbWcgc3JjPQ = "http://www.2cto.com/uploadfile/Collfiles/20140517/20140517091102107.gif" alt = "\">

    Then, when we click this dialog box, intent will be triggered and jump to icationication2activity. java.

    Bytes ----------------------------------------------------------------------------------------

    Note: The id in notify (id, notification) in icationicationmanager is the identifier used to uniquely identify our current notification. This value is passed when we delete a notification through the cancel method. When reading many documents, readers may find that this place has specified an inexplicable value, such as R. drawable. I am wondering why I want to specify an image here. Here I will introduce why?

    The answer is actually very simple. We all know that the only requirement for the parameter here is that the id must be consistent with and unique in the notify method. If the two parameters are met, nothing else. Notify and cancel are consistent. as developers, we are very easy to control, but the only one is that we can't really say it, so here some people are thinking about it, we use the index IDs of image resources or other resources in our system. We all know that these values must be unique!

    Bytes ------------------------------------------------------------------------------------------

    The following are some materials from the Internet:

    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.

    Bytes ------------------------------------------------------------------------------------------------------

    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 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 notification = new Notification ();
    Notification setting process ........
    Nm. Y (0, notification); // it is sent to the status bar.

    Bytes ------------------------------------------------------------------------------------------------------------

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


    Application Instance 3-combined with Broadcast and Broadcast Receiver


    private static final String ACTION_1="com.example.androidbasicdemo1.NEW_BROADCAST_1";private static final String ACTION_2="com.example.androidbasicdemo1.NEW_BROADCAST_2";
    @ Overridepublic boolean onCreateOptionsMenu (Menu menu) {menu. add (0, Menu. FIRST, 0, "display Notification"); menu. add (0, Menu. FIRST + 1, 0, "clear Notification"); return super. onCreateOptionsMenu (menu) ;}@ Overridepublic boolean onOptionsItemSelected (MenuItem item) {int id = item. getItemId (); if (id = Menu. FIRST) {actionClickMenuItem1 (); return true;} if (id = Menu. FIRST + 1) {actionClickMenuItem2 (); return true;} return super. onOptionsItemSelected (item);} private void actionClickMenuItem1 () {Intent intent1 = new Intent (ACTION_1); sendBroadcast (intent1);} private void actionClickMenuItem2 () {Intent intent2 = new Intent (ACTION_2); sendBroadcast (intent2 );}


    Broadcast Receiver1

    Package com. example. broadcastreceiver; import com. example. androidbasicdemo1.DBDemoActivity; import android. r; import android. app. notification; import android. app. icationicationmanager; import android. app. pendingIntent; import android. content. broadcastReceiver; import android. content. context; import android. content. intent;/*** must be in AndroidManifest. register in xml * Custom Broadcast Receiver er inherits BroadcastReceiver * override onReceive () method ** @ author JayHe **/public class MyAndroidReceiver1 extends BroadcastReceiver {private Context context Context; public static int NOTIFICATION_ID = 21321; @ Overridepublic void onReceive (Context context, Intent intent) {this. context = context; showNotification ();} private void showNotification () {icationicationmanager icationmanager = (icationicationmanager) context. getSystemService (android. content. context. NOTIFICATION_SERVICE); Notification notification = new Notification (R. drawable. ic_btn_speak_now, "From MyReceiver1", System. currentTimeMillis (); PendingIntent contentIntent = PendingIntent. getActivity (context, 0, new Intent (context, DBDemoActivity. class), 0); notification. setLatestEventInfo (context, "In MyReceiver1", null, contentIntent); icationicationmanager. Y (ication_id _id, notification );}}

    Broadcast Receiver2

    Package com. example. broadcastreceiver; import android. app. icationicationmanager; import android. content. broadcastReceiver; import android. content. context; import android. content. intent; public class MyAndroidReceiver2 extends BroadcastReceiver {Context context; @ Overridepublic void onReceive (Context context, Intent intent) {this. context = context; deleteNotification ();} // The enotification method returns the generated Notificatio N is deleted from the status bar. /*** Note: each Notification has a unique id, and the id of this Notification in the program is MyAndroidReceiver1.NOTIFICATION _ ID */private void deleteNotification () {icationicationmanager icationmanager = (NotificationManager) context. getSystemService (android. content. context. NOTIFICATION_SERVICE); icationicationmanager. cancel (MyAndroidReceiver1.NOTIFICATION _ ID );}}




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.