Android中的通知—Notification

Android中Notification通知的實現步驟:java

1.獲取NotificationManager對象
NotificationManager的三個公共方法:
①cancel(int id) 取消之前顯示的一個通知.假如是一個短暫的通知,試圖將隱藏,假如是一個持久的通知,將從狀態條中移走。
②cancelAll() 取消之前顯示的全部通知。
③notify(int id,  Notification notification) 把通知持久的發送到狀態條上。android

2.初始化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 通知的時間戳app

注:若是使Notification常駐在狀態欄能夠把Notification的flags屬性設置爲FLAG_ONGOING_EVENTide

n.flags = Notification.FLAG_ONGOING_EVENT

3.設置通知的顯示參數
使用PendingIntent來包裝通知Intent,使用Notification的setLatestEventInfo來設置通知的標題、通知內容等信息。spa

4.發送通知
使用NotificationManager的notify(int id,  Notification notification)方法來發送通知。code

代碼(提示下載完成:)server

// 通知的ID
   public static final int ID = 1;
//提醒
                
                 // 1.獲取NotificationManager對象
                    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                // 2.初始化Notification對象
                    Notification n = new Notification();
                // 設置通知的icon圖標
                n.icon = R.drawable.icon;
                // 設置通知在狀態欄上顯示的滾動信息
                n.tickerText = "下載完成";
                // 設置通知的時間
                n.when = System.currentTimeMillis();
                // 3.設置通知的顯示參數
                Intent intent = new Intent(getApplicationContext(), NotificationView.class);
                PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
                n.setLatestEventInfo(getApplicationContext(), "今日頭條//通知標題", "您要離線內容完成//通知內容", pi);
                // 4.發送通知
                nm.notify(ID, n);
package com.bawei.server;

import com.bawei.jinritioutiao.R;

import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;

public class NotificationView extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.notificationview);
    // 取消通知
    NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    nm.cancel(MyServer.ID);
    finish();
}
}

相關文章
相關標籤/搜索