運行在背景Service,需要某種方式來通知使用者,例如通知使用者來電,通知有新的訊息。這類的通知顯示在status bar上,還可以帶有硬體的提醒,例如震動、LED燈閃,播放聲音等等。在Android中,可以通過NotificationManager來發起一個通知。
我們先看一個簡單的例子,如有圖所示。介面很簡單,兩個大button,上面是出發通知,下面的是取消通知。觸發通知後,狀態列顯示表徵圖和通知摘要(ticker,股市的自動收錄機),幾秒後只剩片,下拉狀態列,這以TextView的方式顯示內容的標題title和文本。點擊通知後,跳到某個activity中。
建立點擊通知後出發的activity,採用簡單方式,使用TextView方式
public class NotifyMessage extends Activity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView t = new TextView(this);
t..setText("This is the message!");
setContentView(t);
}
}
下面是通知的處理常式
public class NotifyTest extends Activity{
private NotificationManager mgr = null;//通過通知管理器來實現通知操作
int count = 0; //有時service會發出多條通知,我們用一個計數器來類比不同的通知
private static final int NOTIFY_ME_ID=1337;
//通知管理器通過通知ID來標識不同的通知,建立和刪除通知是需要提供通知號。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notify_test);
//步驟1:在Android進行通知處理,首先需要重系統哪裡獲得通知管理器NotificationManager,它是一個系統Service。
mgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
}
/*按上面button,出發notifyMe( ) */
public void notifyMe(View v){
count ++; //這是通知的序號,每按一次button,類比一條新的通知
//步驟2:建立一個PendingIntent,和Intent類似,不同的是由於不是馬上調用,需要在下拉狀態條是出發的activity,所以採用的是PendingIntent
PendingIntent i = PendingIntent.getActivity(this, 0, new Intent(this,NotifyMessage.class), 0);
//步驟3:通過Notification.Builder來建立通知,注意這是在API Level 11之後才支援,如果要相容Android 2.x的版本,可以看後面注釋內的代碼
Notification myNotify = new Notification.Builder(this)
.setSmallIcon(R.drawable.note)
//設定狀態列中的小圖片,尺寸一般建議在24×24,這個圖片同樣也是在下拉狀態列中所顯示,如果在那裡需要更換更大的圖片,可以使用setLargeIcon(Bitmap icon)
.setTicker("Ticker:"+count)//設定在status bar上顯示的提示文字
.setContentTitle("Title:" + count)//設定在下拉status bar後Activity,本例子中的NotififyMessage的TextView中顯示的標題
.setContentText("Notification Text" + count)//TextView中顯示的詳細內容
.setContentIntent(i)
//關聯PendingIntent
.setNumber(count)
//在TextView的右方顯示的數字,可放大圖片看,在最右側。這個number同時也起到一個序號的左右,如果多個觸發多個通知(同一ID),可以指定顯示哪一個。
.build();
//需要注意build()是在API level 16增加的,可以使用 getNotificatin()來替代
/* 下面需相容Android 2.x版本是的處理方式
Notification myNotify=new Notification(R.drawable.note, "Ticker:" + count, System.currentTimeMillis());
myNotify.setLatestEventInfo(this, "Notification Title", "This is the notification message", i);
myNotify.number = count; */
myNotify.flags |= Notification.FLAG_AUTO_CANCEL;
//FLAG_AUTO_CANCEL表明當通知被使用者點擊時,通知將被清除。
mgr.notify(NOTIFY_ME_ID ,myNotify);//步驟4:通過通知管理器來發起通知。如果id不同,則每click,在status哪裡增加一個提示
}
/* 按下面的button,觸發消除通知
*/
public void notifyClear(View v){
mgr.cancel( NOTIFY_ME_ID );
}
}
如果通知還需要硬體方面的提醒,例如震動,可如下處理
note.setVibrate(new long[] {500L, 200L, 200L, 500L})
//note.vibrate=new long[] {500L, 200L, 200L, 500L};
Notification.Builder提供了setLights( ),setSound( )等方法,還有其他很多等等,具體可以根據自己的需求在參考中尋找。
相關連結:
我的Android開發相關文章