Notification是一種在手機上面顯示的通知,這篇主要是介紹如何使用,
Android 8.0(api 28 or api 28 up)
在 Android 8.0 中需要 Create 一個 Channel 以便使用者管理 Notification。
Android 8.0 Create Notification 的方法,首先,Create 一個 Channel,必要的參數有 id , Name , Notification.IMPORTANCE_HIGH。
id:Notification Channel 的 id。
Name:Notification Channel 的 名字。
Notification.IMPROTANCE_HIGH:Notification 的優先權,優先權高可以做到 Title Notification 的效果。
description: Returns the user visible description of this channel.(官方解釋)
channel.enableLights:如果 device 支援 notification light 的話,這個參數就有用。
Builder 的方法:
setContentTitle("Hello"):設定 Notification 的 Title。
setSmallIcon(R.drawable.ic_launcher_foreground):設定 Notification 的 icon,如果有比較大的 layout 需要設定 setLargeIcon。
setTicker("狀態列"): Set this flag if you would only like the sound, vibrate and ticker to be played if the notification is not already showing.(官方解釋)
val channel = NotificationChannel(
"Channel ID",
"Channel Name",
NotificationManager.IMPORTANCE_HIGH)
channel.description = "Hello"
channel.enableLights(true)
// Sets whether notifications posted to this channel should display notification lights, on devices that support that feature.
channel.enableVibration(true)
channel.vibrationPattern= longArrayOf(0,1000,1000,1000)
mNotificationManager.createNotificationChannel(channel)
val mBuilder = NotificationCompat.Builder(this, "Channel ID")
mBuilder.setContentTitle("Hello")
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground)
mBuilder.setAutoCancel(true)
mBuilder.setContentInfo("Info")
mBuilder.setTicker("狀態列")
mBuilder.setChannelId("Channel ID")
非 Android 8.0 或 Android 8.0 以下
val mBuilder = NotificationCompat.Builder(this)
mBuilder.setContentTitle("Hello")
mBuilder.setSmallIcon(R.drawable.ic_launcher_foreground)
mBuilder.setAutoCancel(true)
mBuilder.setContentInfo("Info")
mBuilder.setTicker("狀態列")
mBuilder.setPriority(NotificationCompat.PRIORITY_MAX)
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND)
//設定震動方式,延遲0秒,震動1秒,延遲1秒、震動一秒
mBuilder.setVibrate(longArrayOf(0, 1000, 1000, 1000))
Not cancel because user slide
只要在notification設定setOngoing(true),這樣就不會被滑動而取消掉摟~~
mBuilder.setOnGoing(true)
Title Notification
如果想要讓Notification顯示在Title,就像這樣
該怎麼做呢?
關鍵點在於,這幾行,設定優先權以及震動的動作,即可得到title的效果。
Android 8.0 以下
mBuilder.setPriority(NotificationCompat.PRIORITY_MAX)
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND)
//設定震動方式,延遲0秒,震動1秒,延遲1秒、震動一秒
mBuilder.setVibrate(longArrayOf(0, 1000, 1000, 1000))
Android 8.0
設定 Channel
channel.enableVibration(true)
channel.vibrationPattern= longArrayOf(0,1000,1000,1000)