從 Android 8.0 (API 等級 26) 開始,如果相關聯的應用程式有有效通知,系統就會在啟動器圖示上顯示通知徽章 (也稱為通知圓點)。使用者可以按住應用程式圖示,即可顯示通知以及任何應用程式捷徑,如圖 1 所示。
根據預設,這些點會顯示在支援這些點的啟動器應用程式中,因此您的應用程式不需要顯示任何設定。不過,在某些情況下,您可能不希望顯示通知圓點,或想控制要在該處顯示哪些通知。
停用標記功能
在某些情況下,徽章不適合通知,因此您可以在 NotificationChannel
物件上呼叫 setShowBadge(false)
,針對個別管道停用徽章。
例如,您可能會想在下列情況下停用通知標記:
- 持續進行的通知:大部分的持續性通知 (例如圖片處理、媒體播放控制項或目前的導航指示) 不適合做為標記。
- 日曆提醒:避免標記目前時間發生的標記活動。
- 時鐘或鬧鐘事件:避免顯示與目前鬧鐘相關的錯誤通知。
下列程式碼範例示範如何隱藏通知管道的標記:
Kotlin
val id = "my_channel_01" val name = getString(R.string.channel_name) val descriptionText = getString(R.string.channel_description) val importance = NotificationManager.IMPORTANCE_LOW val mChannel = NotificationChannel(id, name, importance).apply { description = descriptionText setShowBadge(false) } val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(mChannel)
Java
String id = "my_channel_01"; CharSequence name = getString(R.string.channel_name); String description = getString(R.string.channel_description); int importance = NotificationManager.IMPORTANCE_LOW; NotificationChannel mChannel = new NotificationChannel(id, name, importance); mChannel.setDescription(description); mChannel.setShowBadge(false); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.createNotificationChannel(mChannel);
設定自訂通知計數
根據預設,每則通知都會增加按住選單上顯示的數字 (如圖 1 所示),但您可以針對應用程式覆寫這個數字。舉例來說,如果您只需要使用一則通知代表多則新訊息,而想計數,這可能表示新訊息總數。
如要設定自訂電話號碼,請針對通知呼叫 setNumber()
,如下所示:
Kotlin
var notification = NotificationCompat.Builder(this@MainActivity, CHANNEL_ID) .setContentTitle("New Messages") .setContentText("You've received 3 new messages.") .setSmallIcon(R.drawable.ic_notify_status) .setNumber(messageCount) .build()
Java
Notification notification = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID) .setContentTitle("New Messages") .setContentText("You've received 3 new messages.") .setSmallIcon(R.drawable.ic_notify_status) .setNumber(messageCount) .build();
修改通知的按住選單圖示
「按住」選單會顯示與通知相關聯的大型或小型圖示 (如有)。根據預設,系統會顯示大型圖示,但您可以呼叫 Notification.Builder.setBadgeIconType()
,並傳入 BADGE_ICON_SMALL
常數以顯示小型圖示。
Kotlin
var notification = NotificationCompat.Builder(this@MainActivity, CHANNEL_ID) .setContentTitle("New Messages") .setContentText("You've received 3 new messages.") .setSmallIcon(R.drawable.ic_notify_status) .setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL) .build()
Java
Notification notification = new NotificationCompat.Builder(MainActivity.this, CHANNEL_ID) .setContentTitle("New Messages") .setContentText("You've received 3 new messages.") .setSmallIcon(R.drawable.ic_notify_status) .setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL) .build();
隱藏重複的快速鍵
如果應用程式建立複製應用程式捷徑的通知,您可以呼叫 setShortcutId()
,在通知啟用期間暫時隱藏捷徑。
如需更多使用通知的程式碼範例,請參閱使用者範例。