.Android Notification 基礎

來源:互聯網
上載者:User

當使用者有沒有接到的電話的時候,Android頂部狀態列裡就會出現一個小表徵圖。提示使用者有沒有處理的快訊,當拖動狀態列時,可以查看這些快訊。Android給我們提供了NotificationManager來管理這個狀態列。可以很輕鬆的完成。

(您想上youtube、facebook嗎?瞭解最新國際國內形勢嗎?請發郵件到freeget.one@gmail.com獲得軟體)

    如果要添加一個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一樣。

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

這裡我們還是一個Demo來掩飾我們的操作。

1:建立一個工程NotificationDemo。

2:添加一個Activity:DesActivity,注意需要在Manifest.xml中聲明

3:NotificationDemo中的Laytout檔案很簡單就是定義一個Button.其代碼檔案如下:

view plaincopy to clipboardprint?
package com.rocky.studio.ch4221;  
import android.app.Activity;  
import android.app.Notification;  
import android.app.NotificationManager;  
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 NotificationDemo extends Activity {  
      
    Button m_Button1;  
    TextView m_txtView;  
      
    NotificationManager 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_NotificationManager=(NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);  

          
                  
        m_Button1=(Button)this.findViewById(R.id.Button01);  
         
          
        //點擊通知時轉移內容  
        m_Intent=new Intent(NotificationDemo.this,DesActivity.class);  
          
        m_PendingIntent=PendingIntent.getActivity(NotificationDemo.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  
                  
                //設定通知在狀態列顯示的表徵圖  
                m_Notification.icon=R.drawable.icon;  
                  
                //當我們點擊通知時顯示的內容  
                m_Notification.tickerText="Button1 通知內容.....";  
                                  
                //通知時發出的預設聲音  
                m_Notification.defaults=Notification.DEFAULT_SOUND;  
                  
                //設定通知顯示的參數  
                m_Notification.setLatestEventInfo(NotificationDemo.this, "Button1", "Button1通知",m_PendingIntent );  

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

package com.rocky.studio.ch4221;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
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 NotificationDemo extends Activity {
 
 Button m_Button1;
 TextView m_txtView;
 
 NotificationManager 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_NotificationManager=(NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);
       
               
        m_Button1=(Button)this.findViewById(R.id.Button01);
      
       
        //點擊通知時轉移內容
        m_Intent=new Intent(NotificationDemo.this,DesActivity.class);
       
        m_PendingIntent=PendingIntent.getActivity(NotificationDemo.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
    
    //設定通知在狀態列顯示的表徵圖
    m_Notification.icon=R.drawable.icon;
    
    //當我們點擊通知時顯示的內容
    m_Notification.tickerText="Button1 通知內容.....";
        
    //通知時發出的預設聲音
    m_Notification.defaults=Notification.DEFAULT_SOUND;
    
    //設定通知顯示的參數
    m_Notification.setLatestEventInfo(NotificationDemo.this, "Button1", "Button1通知",m_PendingIntent );
    
    //這個可以理解為開始執行這個通知
    m_NotificationManager.notify(0,m_Notification);
    
   }});
       
    }
   
   
}

4:修改DesActivity 的源檔案,代碼如下:它做的事情就是取消之前添加的Notification

view plaincopy to clipboardprint?
01.package com.rocky.studio.ch4221;  
02.import android.app.Activity;  
03.import android.app.NotificationManager;  
04.import android.os.Bundle;  
05.public class DesActivity extends Activity {  
06.      
07.    NotificationManager 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.         //啟動後刪除之前我們定義的  
16.         m_NotificationManager=(NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);  

17.         m_NotificationManager.cancel(0);          
18.    }  
19.      
20.} 
package com.rocky.studio.ch4221;
import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;
public class DesActivity extends Activity {
 
 NotificationManager m_NotificationManager;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
   super.onCreate(savedInstanceState);  
   this.setContentView(R.layout.main2);
  
   //啟動後刪除之前我們定義的
   m_NotificationManager=(NotificationManager)this.getSystemService(NOTIFICATION_SERVICE);
   m_NotificationManager.cancel(0);  
 }
 
}
 

代碼也很簡單。可以查看Notification , NotificationMananger 這兩個類來學習前後左右。

下面是一篇文章,對Notification ,NotificationManager這兩個類有詳細的說明介紹,特借鑒一下。

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

 建立和配置新的Notification需要經曆三步。
  
  首先,你要建立一個新的Notification對象,傳入要在狀態條上顯示的圖 標、文字和Notification的 目前時間,如下面的程式碼片段所示:
  
  // 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 notification = new Notification(icon, tickerText, when);
  
  當Notification觸發時,文本將沿著狀態條進行滾動 顯示。

其次,使用setLatestEventInfo方法來配置Notification在擴充的狀態視窗中的外觀。擴充的狀態視窗將顯示表徵圖和在建構函式中傳入的時間,以及顯示標題和一個詳細的字串。Notification一般表示為對一個動作的請求或引起使用者的注意,所以,當使用者點擊Notification項目時你可以指定一個PendingIntent來觸發。

  
  下面的程式碼片段使用了setLastestEventInfo來設定這些值:
  
  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);
  
  一個好的形式是顯示相同事件(例如,接 收多個SMS訊息)的多個對象時 使用一個Notification圖 標。為了呈現給使用者,使用setLastestEventInfo更新資料集來呈現最近的訊息以及重新觸發Notification來更新它的值。

  
  你還可以使用number屬性來顯示一個狀態條表徵圖所表示的事件數目。
  
  設定為比1大的數,如下所示,將在狀態條表徵圖上以一個小小的數字進行 顯示:
  
  notification.number++;
  
  任何對Notification的變更,你都需要重新觸發來進行更 新。如果要刪除這個數字,設定number的值為0或者-1。
  
  最後,你可以對Notification對象使用多種屬性來增強Notification的效果,如閃爍LED、震動電話和播放音樂檔案。這些進階特徵將在本章的後面部分進行詳細描述。

  
  觸發Notification
  
  為了觸發一個Notification,使用NotificationManager的notify方法,將一個整數的ID和Notification對象傳入,如下的片段所示:

  
  int notificationRef = 1;
  notificationManager.notify(notificationRef, notification);
  
  為了更新一個已經觸發過的Notification,傳入相同的ID。你既可以傳入相同的Notification對象,也可以是一個全新的對象。只 要ID相同,新的Notification對象會替換狀態條

表徵圖和擴充的狀態視窗的細節。
  
  你還可以使用ID來取消Notification,通過調用NotificationManager的cancel方法,如下所示:
  
  notificationManager.cancel(notificationRef);
  
  取消一個Notification時,將移除它的狀態條表徵圖以及清除 在擴充的狀態視窗中的資訊。

Notification和NotificationManager的基本使用方法

1. NotificationManager和Notification用來設定通知。

通知的設定等操作相對比較簡單,基本的使用方式就是用建立一個Notification對象,然後設定好通知的各項參數,然後使用系統後台啟動並執行 NotificationManager服務將通知發出來。

基本步驟如下:

1)得到NotificationManager:

String ns = Context.NOTIFICATION_SERVICE;

NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);

 

2)建立一個新的Notification對象:

Notification notification = new Notification();

notification.icon = R.drawable.notification_icon;

 

也可以使用稍微複雜一些的方式建立Notification:

int icon = R.drawable.notification_icon; //通知表徵圖

CharSequence tickerText = "Hello";  //狀態列(Status Bar)顯示的通知文本提示

long when = System.currentTimeMillis(); //通知產生的時間,會在通知資訊裡顯示

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

 

3)填充Notification的各個屬性:

Context context = getApplicationContext();

CharSequence contentTitle = "My notification";

CharSequence contentText = "Hello World!";

Intent notificationIntent = new Intent(this, MyClass.class);

PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

 

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

 

2. 通知的更新

   如果需要更新一個通知,只需要在設定好notification之後,再調用setLatestEventInfo,然後重新發送一次通知即可

 

NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

上面這一句,從系統中獲得Notification服務,getSystemService()就是這麼用,來獲得系統服務的。

 

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

 

然後是構造一個Notification,包括三個屬性,表徵圖,表徵圖後面的文字,以及Notification時間部分顯示出來的時間,通常使用目前時間。FLAG_AUTO_CANCEL說明Notification點擊一次就消失。

 

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

 

上面這部分Code,構造一個Intent,並且放進去一條資訊。 FLAG_ACTIVITY_CLEAR_TOP, FLAG_ACTIVITY_NEW_TASK者兩個FLAG表示優先尋找已經開啟的應用,如果應用沒有開啟那麼啟動它。

 

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

這一句代碼把Intent封裝在PendingIntent裡,this是Context,id是PendingIntent的標誌,如果id相同會被認為是一個。FLAG_UPDATE_CURRENT是指後來的PendingIntent會更新前面的。

 

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

最後這兩行添加狀態列的詳細資料,封裝PendingIntent給Notification,最後發送Notification。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.