文/大大大大峰哥
概述
在我們Android開發過程Notification是一個使用率較高的組件,我們有理由仔細學習它。使用場景一般是在程序進入了后臺的時候我們才需要用到通知。
創建通知
- 首先我們需要創建一個NotificationManager來對通知進行管理。NotificationManager通過調用
Context.getSystemService(Context.NOTIFICATION_SERVICE)
。 - 創建Notification對象,通過
Notification.Builder
創建,必須包含setSmallIcon()
小圖標、setContentTitle()
標題、setContentText()
詳細文本。 - 然后調用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燈,需要使用
ledARGB
,ledOnMS
,ledOffMS
以及flags
屬性來實現。
注意:這里需要寫入震動的權限。
△例子(實現綠色燈一閃一閃):
notification.ledARGB=Color.GREEN;
notification.ledOnMS=1000;
notification.ledOffMS=1000;
notification.flags=FLAG_SHOW_LIGHTS;
使用默認提醒
如果不想麻煩,就直接使用系統默認的提醒,我感覺也不挺不錯的。
notification.defaults=Notification.DEFAULT_ALL;