Notification與Toast都可以起到通知、提醒的作用。但它們的實現原理和表現形式卻完全不一樣。Toast其實相當於一個組件(Widget)。有些類似於沒有按鈕的對話 框。而Notification是顯示在螢幕上方狀態列中的資訊。還有就是Notification需要用NotificationManager來管理,而Toast只需要簡單地建立Toast對象即可。
下面來看一下建立並顯示一個Notification的步驟。建立和顯 示一個Notification需要如下5步:
1. 通過getSystemService方法獲得一個NotificationManager對象。
2. 建立一個Notification對象。每一個Notification對應一個Notification對象。在這一步需要設定顯示在螢幕上方狀態列的通知訊息、通知訊息前方的映像資源ID和發出通知的時間。一般為目前時間。
3. 由於Notification可以與應用程式脫離。也就是說,即使應用程式被關閉,Notification仍然會顯示在狀態列 中。當應用程式再次啟動後,又可以重新控制這些Notification。如清除或替換它們。因此,需要建立一個PendingIntent對象。該對象由Android系統負責維護,因此,在應用程式關閉後,該對象仍然不會被釋放。
4. 使用Notification類的setLatestEventInfo方法設定Notification的詳細資料。
5. 使用NotificationManager類的notify方法顯示Notification訊息。在這一步需要指定標識Notification的唯一ID。這個ID必須相對於同一個NotificationManager對象是唯一的,否則就會覆蓋相同ID的Notificaiton。
心動不如行動,下面我們來演練一下如何在狀 態欄顯示一個Notification,代碼如下:
java代碼:
- // 第1步
- NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
- // 第2步
- Notification notification = new Notification(R.drawable.icon, "您有新訊息了", System.currentTimeMillis());
- // 第3步
- PendingIntent contentIntent = PendingIntent.getActivity(this, 0, getIntent(), 0);
- // 第4步
- notification.setLatestEventInfo(this, "天氣預報", "晴 轉多雲", contentIntent);
- // 第5步
- notificationManager.notify(R.drawable.icon, notification);
- showNotification("今 天非常高興", "今天考試得了全年級第一",
- "數學100分、語文99分、英語100分,yeah!", R.drawable.smile, R.drawable.smile);
- showNotification("這是為什麼呢?", "這 道題為什麼會出錯呢?", "誰有正確答案啊.",
- R.drawable.why, R.drawable.why);
- showNotification("今天心情不好", "也 不知道為什麼,這幾天一直很鬱悶.", "也許應該去公園散心了",
- R.drawable.why, R.drawable.wrath);
複製代碼
系列之Android Notification與Toast(二)的文章連結http://www.eoeandroid.com/thread-81330-1-1.html