Android開發之通知欄Notification詳解

來源:互聯網
上載者:User

Notification的用法 --- 狀態列通知


發送一個狀態列通知必須的兩個類:

1. NotificationManager --- 狀態列通知的管理類,負責發通知,清除通知等
NotificationManager : 是一個系統Service,必須通過 context.getSystemService(NOTIFICATION_SERVICE)方法擷取
NotificationManager notificationManager = (NotificationManager) context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);


2. Notification --- 具體的狀態列通知對象,可以設定icon,文字,提示音,震動等參數
下面是設定一個通知需要的基本參數
Anicon(通知的表徵圖)
Atitleanexpandedmessage(通知的標題和內容)
APendingIntent(點擊通知執行頁面跳轉)

1.建立Notification
通過NotificationManager的notify(int Id , Notification)方法來啟動Notification
參數一:Notification的唯一標識
參數二:Notification對象

2.更新Notification
調用Notification的setLatestEventInfo()方法來更新內容,然後調用NotificationManager的notify()方法即可

3.刪除Notification
通過NotificationManager的cancle(int id) 方法,清除通知 參數: 要清除的Notification的唯一標識

4.Notification設定 -- 震動,鈴聲等

1.基本設定:

//建立狀態列通知 baseNF=new Notification(); //設定通知在狀態列顯示的表徵圖 baseNF.icon=R.drawable.icon; //通知時在狀態列顯示的內容 baseNF.tickerText="YouclickedBaseNF!"; //通知的預設參數DEFAULT_SOUND,DEFAULT_VIBRATE,DEFAULT_LIGHTS. //如果要全部採用預設值,用DEFAULT_ALL. //此處採用預設聲音 baseNF.defaults=Notification.DEFAULT_SOUND; //第二個參數:下拉狀態列時顯示的訊息標題expandedmessagetitle //第三個參數:下拉狀態列時顯示的訊息內容expandedmessagetext //第四個參數:點擊該通知時執行頁面跳轉 baseNF.setLatestEventInfo(Lesson_10.this,"Title01","Content01",pd); //發出狀態列通知 //ThefirstparameteristheuniqueIDfortheNotification //andthesecondistheNotificationobject. nm.notify(Notification_ID_BASE,baseNF); 

2.添加聲音

baseNF.default=Notification.DEFAULT_SOUND; -- 使用系統預設提示音

notification.sound=Uri.parse("file:///sdcard/notification/ringer.mp3"); --- 自訂聲音

使用用系統內建的鈴聲,可以這樣:

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

3.添加震動

notification.defaults|=Notification.DEFAULT_VIBRATE; 使用預設震動方式

4.添加閃光

notification.defaults|=Notification.DEFAULT_LIGHTS;

5.其他有用的設定:

flags: Notification.FLAG_INSISTENT;//讓聲音、震動無限迴圈,直到使用者響應 Notification.FLAG_AUTO_CANCEL;//通知被點擊後,自動消失 Notification.FLAG_NO_CLEAR;//點擊'Clear'時,不清楚該通知(QQ的通知無法清除,就是用的這個 //自訂下拉視圖,比如下載軟體時,顯示的進度條。 Notificationnotification=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,thismessageisinacustomexpandedview"); notification.contentView=contentView; //使用自訂下拉視圖時,不需要再調用setLatestEventInfo()方法 //但是必須定義contentIntent notification.contentIntent=pd; nm.notify(3,notification); 

應用執行個體一:

根據activity的生命週期,在activity不顯示時,會執行onStop函數(比如按下home鍵),所以你在onStop函數(按退出鍵除外)裡面把notification放在通知欄裡,再此顯示時,把notification從通知欄裡去掉。或者,只要程式在運行就一直顯示通知欄表徵圖。     下面對Notification類中的一些常量,欄位,方法簡單介紹一下:常量:DEFAULT_ALL    使用所有預設值,比如聲音,震動,閃屏等等DEFAULT_LIGHTS 使用預設閃光提示DEFAULT_SOUNDS 使用預設提示聲音DEFAULT_VIBRATE 使用預設手機震動 【說明】:加入手機震動,一定要在manifest.xml中加入許可權:以上的效果常量可以疊加,即通過notification.defaults =DEFAULT_SOUND|DEFAULT_VIBRATE;  notification.defaults |= DEFAULT_SOUND (最好在真機上測試,震動效果模擬器上沒有)            //設定flag位FLAG_AUTO_CANCEL  該通知能被狀態列的清除按鈕給清除掉FLAG_NO_CLEAR     該通知能被狀態列的清除按鈕給清除掉FLAG_ONGOING_EVENT 通知放置在正在運行FLAG_INSISTENT 是否一直進行,比如音樂一直播放,知道使用者響應          常用欄位:contentIntent  設定PendingIntent對象,點擊時發送該Intentdefaults 添加預設效果flags 設定flag位,例如FLAG_NO_CLEAR等icon 設定表徵圖sound 設定聲音tickerText 顯示在狀態列中的文字when 發送此通知的時間戳記                NotificationManager常用方法介紹:public void cancelAll() 移除所有通知(只是針對當前Context下的Notification)public  void cancel(int id) 移除標記為id的通知 (只是針對當前Context下的所有Notification)public  void notify(String tag ,int id, Notification notification) 將通知加入狀態列,標籤為tag,標記為idpublic  void notify(int id, Notification notification) 將通知加入狀態列,標記為idpackage com.ljq.activity; import android.app.Activity;import android.app.Notification;import android.app.NotificationManager;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();    }         /**     * 在狀態列顯示通知     */    private void showNotification(){        // 建立一個NotificationManager的引用           NotificationManager notificationManager = (NotificationManager)                this.getSystemService(android.content.Context.NOTIFICATION_SERVICE);                    // 定義Notification的各種屬性           Notification notification =new Notification(R.drawable.icon,                   "督導系統", System.currentTimeMillis());         //FLAG_AUTO_CANCEL   該通知能被狀態列的清除按鈕給清除掉        //FLAG_NO_CLEAR      該通知不能被狀態列的清除按鈕給清除掉        //FLAG_ONGOING_EVENT 通知放置在正在運行        //FLAG_INSISTENT     是否一直進行,比如音樂一直播放,知道使用者響應        notification.flags |= Notification.FLAG_ONGOING_EVENT; // 將此通知放到通知欄的"Ongoing"即"正在運行"組中           notification.flags |= Notification.FLAG_NO_CLEAR; // 表明在點擊了通知欄中的"清除通知"後,此通知不清除,經常與FLAG_ONGOING_EVENT一起使用           notification.flags |= Notification.FLAG_SHOW_LIGHTS;           //DEFAULT_ALL     使用所有預設值,比如聲音,震動,閃屏等等        //DEFAULT_LIGHTS  使用預設閃光提示        //DEFAULT_SOUNDS  使用預設提示聲音        //DEFAULT_VIBRATE 使用預設手機震動,需加上許可權        notification.defaults = Notification.DEFAULT_LIGHTS;         //疊加效果常量        //notification.defaults=Notification.DEFAULT_LIGHTS|Notification.DEFAULT_SOUND;        notification.ledARGB = Color.BLUE;           notification.ledOnMS =5000; //閃光時間,毫秒                 // 設定通知的事件訊息           CharSequence contentTitle ="督導系統標題"; // 通知欄標題           CharSequence contentText ="督導系統內容"; // 通知欄內容           Intent notificationIntent =new Intent(MainActivity.this, MainActivity.class); // 點擊該通知後要跳轉的Activity           PendingIntent contentItent = PendingIntent.getActivity(this, 0, notificationIntent, 0);           notification.setLatestEventInfo(this, contentTitle, contentText, contentItent);                    // 把Notification傳遞給NotificationManager           notificationManager.notify(0, notification);       }?    //刪除通知        private void clearNotification(){        // 啟動後刪除之前我們定義的通知           NotificationManager notificationManager = (NotificationManager) this                 .getSystemService(NOTIFICATION_SERVICE);           notificationManager.cancel(0);       }}

應用執行個體二:

我們在用手機的時候,如果來了簡訊,而我們沒有點擊查看的話,是不是在手機的最上邊的狀態列裡有一個簡訊的小表徵圖提示啊?你是不是也想實現這種功能呢?今天的Notification就是解決這個問題的。

[java] view plaincopy
  1. package cn.com.chenzheng_java;
  2. import android.app.Activity;
  3. import android.app.Notification;
  4. import android.app.NotificationManager;
  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 狀態列通知相關
  15. * @author chenzheng_java
  16. *
  17. */
  18. public class NotificationActivity 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. * 添加一個notification
  33. */
  34. private void addNotificaction() {
  35. NotificationManager manager = (NotificationManager) this
  36. .getSystemService(Context.NOTIFICATION_SERVICE);
  37. // 建立一個Notification
  38. Notification notification = new Notification();
  39. // 設定顯示在手機最上邊的狀態列的表徵圖
  40. notification.icon = R.drawable.excel;
  41. // 噹噹前的notification被放到狀態列上的時候,提示內容
  42. notification.tickerText = "注意了,我被扔到狀態列了";
  43. /***
  44. * notification.contentIntent:一個PendingIntent對象,當使用者點擊了狀態列上的表徵圖時,該Intent會被觸發
  45. * notification.contentView:我們可以不在狀態列放表徵圖而是放一個view
  46. * notification.deleteIntent 噹噹前notification被移除時執行的intent
  47. * notification.vibrate 當手機震動時,震動周期設定
  48. */
  49. // 添加聲音提示
  50. notification.defaults=Notification.DEFAULT_SOUND;
  51. // audioStreamType的值必須AudioManager中的值,代表著響鈴的模式
  52. notification.audioStreamType= android.media.AudioManager.ADJUST_LOWER;
  53. //下邊的兩個方式可以添加音樂
  54. //notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");
  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. // 點擊狀態列的表徵圖出現的提示資訊設定
  59. notification.setLatestEventInfo(this, "內容提示:", "我就是一個測試檔案", pendingIntent);
  60. manager.notify(1, notification);
  61. }
  62. }

    點擊按鈕時候,狀態列會顯示:

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

    然後,當我們點擊這個對話方塊之後,就會觸發intent,跳轉到Notification2Activity.java這個activity。

    ----------------------------------------------------------------------------------------

    注意,NotificationManager裡的notify(id,notification)中的id是用來唯一標識我們當前的這個notification的標識符,我們通過cancel方法刪除通知時,傳遞的就是這個值。可能讀者在看很多文檔的時候,發現這個地方指定了一個莫名奇妙的值,例如R.drawable.icon,很多朋友就納悶了,為什麼這裡要指定一個圖片呢。這裡筆者就介紹下,為什麼呢?

    答案其實很簡單,我們都知道,我們這裡對參數的唯一要求就是,這個id要和notify方法中的一致,並且是唯一;只要滿足了這兩項,其他的都無所謂。notify和cancel裡一致我們作為開發人員,太好控制了,但是唯一呢,我們還真不好說,於是這裡就有些人動小腦筋了,很巧妙的用了我們系統中的圖片資源或者其他資源的索引ID,我們都知道,這些值肯定都是唯一的!

    ------------------------------------------------------------------------------------------

    下面是從網上找的一些資料:

    如果要添加一個Notification,可以按照以下幾個步驟

    1:擷取NotificationManager:

    NotificationManager m_NotificationManager=(NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);

    2:定義一個Notification:

    Notification m_Notification=new Notification();

    3:設定Notification的各種屬性:

    //設定通知在狀態列顯示的表徵圖
    m_Notification.icon=R.drawable.icon;

    //當我們點擊通知時顯示的內容
    m_Notification.tickerText="Button1 通知內容.....";

    通知時發出的預設聲音
    m_Notification.defaults=Notification.DEFAULT_SOUND;

    //設定通知顯示的參數

    Intent m_Intent=new Intent(NotificationDemo.this,DesActivity.class);
    PendingIntent m_PendingIntent=PendingIntent.getActivity(NotificationDemo.this, 0, m_Intent, 0);

    m_Notification.setLatestEventInfo(NotificationDemo.this, "Button1", "Button1通知",m_PendingIntent );

    //這個可以理解為開始執行這個通知
    m_NotificationManager.notify(0,m_Notification);

    4:既然可以增加同樣我們也可以刪除。當然是只是刪除你自己增加的。

    m_NotificationManager.cancel(0);

    這裡的0是一個ID號碼,和notify第一個參數0一樣。

    這也就完成了,添加刪除工作。

    ------------------------------------------------------------------------------------------------------

    NoticificationManager很容易可以放在狀態列,也很容易實現從statusbar進入程式 中,
    NoticificationManager中通過intent執行此程式的activity就可以了

    NoticificationManager狀態列操作

    NotificationManager(通知管理器):
    NotificationManager負責通知使用者事件的發生.
    NotificationManager有三個公用方法:
    1. cancel(int id) 取消以前顯示的一個通知.假如是一個短暫的通知,試圖將隱藏,假如是一個持久的通知,將從狀態條中移走.
    2. cancelAll() 取消以前顯示的所有通知.
    3. notify(int id, Notification notification) 把通知持久的發送到狀態條上.


    //初始化NotificationManager:
    NotificationManager nm =
    (NotificationManager)getSystemService(NOTIFICATION_SERVICE);

    Notification代表著一個通知.
    Notification的屬性:
    audioStreamType 當聲音響起時,所用的音頻流的類型
    contentIntent 當通知條目被點擊,就執行這個被設定的Intent.
    contentView 當通知被顯示在狀態條上的時候,同時這個被設定的視圖被顯示.
    defaults 指定哪個值要被設定成預設的.
    deleteIntent 當使用者點擊"Clear All Notifications"按鈕區刪除所有的通知的時候,這個被設定的Intent被執行.
    icon 狀態條所用的圖片.
    iconLevel 假如狀態條的圖片有幾個層級,就設定這裡.
    ledARGB LED燈的顏色.
    ledOffMS LED關閉時的閃光時間(以毫秒計算)
    ledOnMS LED開始時的閃光時間(以毫秒計算)
    number 這個通知代表事件的號碼
    sound 通知的聲音
    tickerText 通知被顯示在狀態條時,所顯示的資訊
    vibrate 震動模式.
    when 通知的時間戳記.

    將Notification發送到狀態條上:
    Notification notification = new Notification();
    Notification的設定過程……..
    nm.notify(0, notification); //發送到狀態條上

    ------------------------------------------------------------------------------------------------------------

    Notification提供了豐富的手機提示方式:

    a)在狀態列(Status Bar)顯示的通知文本提示,如:

    notification.tickerText = "hello";

    b)發出提示音,如:

    notification.defaults = Notification.DEFAULT_SOUND;

    notification.sound = Uri.parse("file:///sdcard/notification/ringer.mp3");

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

    c)手機震動,如:

    notification.defaults = Notification.DEFAULT_VIBRATE;

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

    notification.vibrate = vibrate;

    d)LED燈閃爍,如:

    notification.defaults = Notification.DEFAULT_LIGHTS;

    notification.ledARGB = 0xff00ff00;

    notification.ledOnMS = 300;

    notification.ledOffMS = 1000;

    notification.flags = Notification.FLAG_SHOW_LIGHTS;

    4)發送通知:

    private static final int ID_NOTIFICATION = 1;

    mNotificationManager.notify(ID_NOTIFICATION, notification);


    應用執行個體3 ---- 結合Broadcast 和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,"顯示Notification");menu.add(0,Menu.FIRST+1,0,"清楚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.NotificationManager;import android.app.PendingIntent;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;/** * 必須在AndroidManifest.xml中進行註冊 * 自訂Broadcast Receiver繼承BroadcastReceiver * 重寫onReceive()方法 *  * @author JayHe  * */public class MyAndroidReceiver1 extends BroadcastReceiver {private Context context;public static int NOTIFICATION_ID=21321;@Overridepublic void onReceive(Context context, Intent intent) {this.context = context;showNotification();}private void showNotification() {NotificationManager notificationManager = (NotificationManager) context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);Notification notification = new Notification(R.drawable.ic_btn_speak_now, "來自MyReceiver1中", System.currentTimeMillis());PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context,DBDemoActivity.class), 0);notification.setLatestEventInfo(context, "在MyReceiver1中", null, contentIntent);notificationManager.notify(NOTIFICATION_ID, notification);}}

    Broadcast Receiver2

    package com.example.broadcastreceiver;import android.app.NotificationManager;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();}//deleteNotification方法將剛產生的Notification從狀態列刪除。/** * 注意:每一個Notification都有一個唯一的id記性標識,而在程式中的這個Notification的id為MyAndroidReceiver1.NOTIFICATION_ID */private void deleteNotification() {NotificationManager notificationManager = (NotificationManager) context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);notificationManager.cancel(MyAndroidReceiver1.NOTIFICATION_ID);}}




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.