Android Notification學習

文/大大大大峰哥

概述

在我們Android開發過程Notification是一個使用率較高的組件,我們有理由仔細學習它。使用場景一般是在程序進入了后臺的時候我們才需要用到通知。

創建通知

  1. 首先我們需要創建一個NotificationManager來對通知進行管理。NotificationManager通過調用Context.getSystemService(Context.NOTIFICATION_SERVICE)
  2. 創建Notification對象,通過Notification.Builder創建,必須包含setSmallIcon()小圖標、 setContentTitle()標題、setContentText()詳細文本。
  3. 然后調用NotificationManager的notify方法傳入兩個參數:id與Notification對象。

PendingIntent

在我們日常使用APP的時候,我們會發現通知欄的消息我們點擊后,會進入一個新的Activity,這個就是通過PendingIntent實現的。PendingIntent與Intent類似,但是它是一個延時執行的Intent。

創建方法

使用PendingIntent我們是通過PendingIntent自身的getActivity方法,需要傳入四個參數:Conten、第二個參數一般用不到傳0即可、第三個參數為Intent對象、第四個參數為PendingIntent行為

PendingIntent行為:

  • FLAG_ONE_SHOT:Flag indicating that this PendingIntent can be used only once.
  • FLAG_NO_CREATE:Flag indicating that if the described PendingIntent does not already exist, then simply return null instead of creating it.
  • FLAG_CANCEL_CURRENT:Flag indicating that if the described PendingIntent already exists,the current one should be canceled before generating a new one.
  • FLAG_UPDATE_CURRENT:Flag indicating that if the described PendingIntent already exists, then keep it but replace its extra data with what is in this new Intent.
  • FLAG_IMMUTABLE:Flag indicating that the created PendingIntent should be immutable. This means that the additional intent argument passed to the send methods to fill in unpopulated properties of this intent will be ignored.

手動取消

NotificationManager.cancle(id)

通知的高級技巧

  • 設置提醒聲音:sound屬性。
  • 設置震動:vibrat屬性,傳入long數組,前一個為靜止時長,后一個為震動時長。
  • 設置LED燈,需要使用ledARGBledOnMSledOffMS以及flags屬性來實現。

注意:這里需要寫入震動的權限。

△例子(實現綠色燈一閃一閃):

notification.ledARGB=Color.GREEN;
notification.ledOnMS=1000;
notification.ledOffMS=1000;
notification.flags=FLAG_SHOW_LIGHTS;

使用默認提醒
如果不想麻煩,就直接使用系統默認的提醒,我感覺也不挺不錯的。

notification.defaults=Notification.DEFAULT_ALL;

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 原文出處: http://www.androidchina.net/6174.html Notification在...
    木木00閱讀 12,396評論 3 32
  • 轉載自:http://blog.csdn.net/vipzjyno1/article/details/252480...
    HEXG_閱讀 5,935評論 0 2
  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa閱讀 8,926評論 0 6
  • 『我們就像流星,毫無目標地飛逝 不知會消失在何方 但三個人緊緊連在一起,不論遇到什么都不 ...
    三三的歌閱讀 322評論 0 0
  • 一生很長 長得令人無法想象 無法丈量 走過了一季又一季 走過了山高水長 心際的憧憬依然在遠方…… 一生很短 短的來...
    愛已無聲閱讀 265評論 2 10