Android Notification與Toast(一)

來源:互聯網
上載者:User

  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. //  第1步
  2. NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  3. //  第2步
  4. Notification notification = new Notification(R.drawable.icon, "您有新訊息了", System.currentTimeMillis());
  5. //  第3步
  6. PendingIntent contentIntent = PendingIntent.getActivity(this, 0, getIntent(), 0);
  7. //  第4步
  8. notification.setLatestEventInfo(this, "天氣預報", "晴 轉多雲", contentIntent);
  9. //  第5步
  10. notificationManager.notify(R.drawable.icon, notification);
  11. showNotification("今 天非常高興", "今天考試得了全年級第一",
  12.         "數學100分、語文99分、英語100分,yeah!", R.drawable.smile, R.drawable.smile);
  13. showNotification("這是為什麼呢?", "這 道題為什麼會出錯呢?", "誰有正確答案啊.",
  14.         R.drawable.why, R.drawable.why);
  15. showNotification("今天心情不好", "也 不知道為什麼,這幾天一直很鬱悶.", "也許應該去公園散心了",
  16.         R.drawable.why, R.drawable.wrath);

複製代碼



系列之Android Notification與Toast(二)的文章連結http://www.eoeandroid.com/thread-81330-1-1.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.