Android的狀態列通知(Notification)
如果需要查看訊息,可以拖動狀態列到螢幕下方即可查看訊息。
步驟:
1
擷取通知管理器NotificationManager,它也是一個系統服務
2
建立通知Notification notification = new Notification(icon, null, when);
3
為新通知設定參數(比如聲音,震動,燈光閃爍)
4
把新通知添加到通知管理器
發送訊息的代碼如下:
//擷取通知管理器
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)
int icon = android.R.drawable.stat_notify_chat;
long when = System.currentTimeMillis();//通知發生的時間為系統目前時間
//建立一個通知,指定其表徵圖和標題
Notification notification = new Notification(icon, null, when);//第一個參數為表徵圖,第二個參數為短暫提示標題,第三個為通知時間
notification.defaults = Notification.DEFAULT_SOUND;//發出預設聲音
notification.flags |= Notification.FLAG_AUTO_CANCEL;//點擊通知後自動清除通知
Intent openintent = new Intent(this, OtherActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, openintent,
0);//當點擊訊息時就會向系統發送openintent意圖
notification.setLatestEventInfo(this, “標題”,
“我是內容", contentIntent);
mNotificationManager.notify(0, notification);//第一個參數為自訂的通知唯一標識
重點是setLatestEventInfo( )方法的最後一個參數!!!!它是一個PendingIntent!!!!!!!!!
這裡使用到了PendingIntent(pend本意是待定,不確定的意思)
PendingIntent可以看作是對Intent的封裝。PendingIntent主要持有的資訊是它所封裝的Intent和當前Application的Context。正由於PendingIntent中儲存有當前Application的Context,使它賦予帶他程式一種執行的Intent的能力,就算在執行時當前Application已經不存在了,也能通過存在PendingIntent裡的Context照樣執行Intent。
PendingIntent的一個很好的例子:
SmsManager的用於傳送簡訊的方法:
sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliveryIntent);
第一個參數:destinationAddress
對方手機號碼
第二個參數:scAddress
簡訊中心號碼
一般設定為空白
第三個參數:text
簡訊內容
第四個參數:sentIntent判斷簡訊是否發送成功,如果你沒有SIM卡,或者網路中斷,則可以通過這個itent來判斷。注意強調的是“發送”的動作是否成功。那麼至於對於對方是否收到,另當別論
第五個參數:deliveryIntent當簡訊發送到收件者時,會收到這個deliveryIntent。即強調了“發送”後的結果
就是說是在"簡訊發送成功"和"對方收到此簡訊"才會啟用
sentIntent和deliveryIntent這兩個Intent。這也相當於是順延強制了Intent