
第十課:Notification Manager
本文介紹如何使用notification manager。Notification manager管理各notification。換句話說notification manager就是用來顯示來自不同apps的notification。android的screen最頂就有一個notification bar,左邊就是用來顯示剛收到的notification,和notification的圖示。它是個系統提供的service。
我們很多時候會用到notification,如我們有一個音樂播放的service,由於沒有UI,當它要顯示一些status或通知時,便可以用notification。我們自己不會顯示notification,因此要借notification manager的幫助。以下coding可以找出notification manager:
NotificationManager mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Notification包含icon,一個tickerText,就是當系統剛收到後,馬上在最頂那個notification bar中顯示的文字。 Notification還支援振動等其他功能。
Notification n = new Notification(); n.icon = R.drawable.icon; n.tickerText = "Notification ticker text"; n.when = System.currentTimeMillis();
Android使用者可以把頂部的notification bar拉下成為一頁。它顯示了一些最新的通知。這功能使用方法如下:
Intent notificationIntent = new Intent(this, MyClass.class); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); CharSequence contentText = "Content Text"; CharSequence contentTitle = "Content Title"; n.setLatestEventInfo(this, contentTitle, contentText, contentIntent);
我們使用setLatestEventInfo()去設定通知的title和內容,當用戶按下通知時,便會跳到一個activity。 在android的世界中,由一個activity跳到令一個activity就要使用intent。由於你不是由自己的activity跳出, 你現在是把這個intent的資料交給notification manager,當用戶按下notification manager的通知才執行該intent。
Pending intent就好像包裝好intent一樣,當其他apps收到這pending intent,便會知道真正要執行的intent是什麼,而 且pending intent會把執行這intent的權力也一同發出。Pending intent就像是個reference。
現在的情況是把一個intent先以pending intent包裝,然後放到notification中,一同發到notification manager。 Notification manager在顯示notification的同時,也得到了那個intent的權力。當用戶留意到該notification并按下時 ,就可以跳到你想顯示的activity。
以下是通過notification manager把這notification發出的方式。
mNM.notify(NOTIFICATION_ID, n);
NOTIFICATION_ID是一個自定的constant,因為我們可能需要取消某一個notification。
mNM.cancel(NOTIFICATION_ID);
Download: NotificationDemo