通知可在应用未运行时提供有关应用事件的简短、及时的信息。本文档向您展示了如何创建具有各种功能的通知。如需了解通知在 Android 上的显示方式,请参阅通知概览。如需查看使用通知的示例代码,请参阅 GitHub 上的 SociaLite 示例。
本页中的代码使用 AndroidX 库的 NotificationCompat
API。这些 API 可让您添加仅在较新版本的 Android 上可用的功能,同时仍提供对 Android 9(API 级别 28)的兼容性。但是,某些功能(例如行内回复操作)在早期版本上不会执行任何操作。
添加 AndroidX Core 库
虽然大多数使用 Android Studio 创建的项目都包含使用 NotificationCompat
所需的依赖项,但请验证您的模块级 build.gradle
文件是否包含以下依赖项
Groovy
dependencies { implementation "androidx.core:core-ktx:1.16.0" }
Kotlin
dependencies { implementation("androidx.core:core-ktx:1.16.0") }
创建基本通知
通知最基本、最紧凑的形式(也称为折叠形式)会显示图标、标题和少量文本内容。本部分展示了如何创建用户可以点按以在应用中启动 Activity 的通知。
图 1. 包含图标、标题和部分文本的通知。
如需了解通知各部分的更多详情,请阅读通知结构。
声明运行时权限
Android 13(API 级别 33)及更高版本支持运行时权限,用于从应用发布非豁免(包括前台服务 (FGS))通知。
您需要在应用的清单文件中声明的权限显示在以下代码片段中
<manifest ...> <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/> <application ...> ... </application> </manifest>
如需详细了解运行时权限,请参阅通知运行时权限。
设置通知内容
首先,使用 NotificationCompat.Builder
对象设置通知的内容和渠道。以下示例展示了如何创建包含以下内容的通知
通过
setSmallIcon()
设置的小图标。这是唯一必需的用户可见内容。通过
setContentTitle()
设置的标题。通过
setContentText()
设置的正文文本。通过
setPriority()
设置的通知优先级。优先级决定了通知在 Android 7.1 及更早版本上的侵扰程度。对于 Android 8.0 及更高版本,请改为设置渠道重要性,如下一节所示。
Kotlin
var builder = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle(textTitle) .setContentText(textContent) .setPriority(NotificationCompat.PRIORITY_DEFAULT)
Java
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle(textTitle) .setContentText(textContent) .setPriority(NotificationCompat.PRIORITY_DEFAULT);
NotificationCompat.Builder
构造函数要求您提供渠道 ID。这是为了兼容 Android 8.0(API 级别 26)及更高版本,但早期版本会忽略它。
默认情况下,通知的文本内容会被截断以适合一行。您可以通过创建可展开通知来显示其他信息。
图 2. 可展开通知的折叠和展开形式。
如果您希望通知内容更长,可以通过添加样式模板(使用 setStyle()
)来启用可展开通知。例如,以下代码创建了一个更大的文本区域
Kotlin
var builder = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("My notification") .setContentText("Much longer text that cannot fit one line...") .setStyle(NotificationCompat.BigTextStyle() .bigText("Much longer text that cannot fit one line...")) .setPriority(NotificationCompat.PRIORITY_DEFAULT)
Java
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("My notification") .setContentText("Much longer text that cannot fit one line...") .setStyle(new NotificationCompat.BigTextStyle() .bigText("Much longer text that cannot fit one line...")) .setPriority(NotificationCompat.PRIORITY_DEFAULT);
有关其他大型通知样式(包括如何添加图片和媒体播放控件)的更多信息,请参阅创建可展开通知。
创建渠道并设置重要性
在 Android 8.0 及更高版本上投递通知之前,您必须通过将 NotificationChannel
实例传递给 createNotificationChannel()
,将应用的通知渠道注册到系统。以下代码受 SDK_INT
版本的条件限制
Kotlin
private fun createNotificationChannel() { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is not in the Support Library. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val name = getString(R.string.channel_name) val descriptionText = getString(R.string.channel_description) val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(CHANNEL_ID, name, importance).apply { description = descriptionText } // Register the channel with the system. val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.createNotificationChannel(channel) } }
Java
private void createNotificationChannel() { // Create the NotificationChannel, but only on API 26+ because // the NotificationChannel class is not in the Support Library. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = getString(R.string.channel_name); String description = getString(R.string.channel_description); int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance); channel.setDescription(description); // Register the channel with the system; you can't change the importance // or other notification behaviors after this. NotificationManager notificationManager = getSystemService(NotificationManager.class); notificationManager.createNotificationChannel(channel); } }
由于您必须在 Android 8.0 及更高版本上发布任何通知之前创建通知渠道,因此请在应用启动后立即执行此代码。重复调用此方法是安全的,因为创建现有通知渠道不会执行任何操作。
NotificationChannel
构造函数需要一个 importance
参数,它使用 NotificationManager
类中的常量之一。此参数确定如何为属于此渠道的任何通知打断用户。如上例所示,使用 setPriority()
设置优先级以支持 Android 7.1 及更早版本。
尽管您必须设置通知重要性或优先级(如下例所示),但系统并不保证您获得的提醒行为。在某些情况下,系统可能会根据其他因素更改重要性级别,并且用户始终可以重新定义给定渠道的重要性级别。
有关不同级别含义的更多信息,请参阅通知重要性级别。
设置通知的点按操作
每个通知都必须响应点按,通常是为了在您的应用中打开与该通知对应的 Activity。为此,您需要使用 PendingIntent
对象指定内容 intent,并将其传递给 setContentIntent()
。
以下代码片段展示了如何创建一个基本 intent,以便在用户点按通知时打开 Activity
Kotlin
// Create an explicit intent for an Activity in your app. val intent = Intent(this, AlertDetails::class.java).apply { flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK } val pendingIntent: PendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE) val builder = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("My notification") .setContentText("Hello World!") .setPriority(NotificationCompat.PRIORITY_DEFAULT) // Set the intent that fires when the user taps the notification. .setContentIntent(pendingIntent) .setAutoCancel(true)
Java
// Create an explicit intent for an Activity in your app. Intent intent = new Intent(this, AlertDetails.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("My notification") .setContentText("Hello World!") .setPriority(NotificationCompat.PRIORITY_DEFAULT) // Set the intent that fires when the user taps the notification. .setContentIntent(pendingIntent) .setAutoCancel(true);
此代码调用 setAutoCancel()
,当用户点按通知时,此方法会自动移除该通知。
上例中的 intent 标志保留了用户通过通知打开应用后的预期导航体验。您可能希望根据您启动的 Activity 类型来使用它,Activity 类型可以是以下之一
专为响应通知而存在的 Activity。用户在正常使用应用期间没有理由导航到此 Activity,因此此 Activity 会启动一个新任务,而不是添加到应用现有的任务和返回堆栈中。这是上例中创建的 intent 类型。
存在于应用常规流程中的 Activity。在这种情况下,启动此 Activity 会创建返回堆栈,以便保留用户对返回和向上按钮的预期。
有关配置通知 intent 的不同方式的更多信息,请参阅从通知启动 Activity。
显示通知
要显示通知,请调用 NotificationManagerCompat.notify()
,并向其传递通知的唯一 ID 以及 NotificationCompat.Builder.build()
的结果。如下例所示
Kotlin
with(NotificationManagerCompat.from(this)) { if (ActivityCompat.checkSelfPermission( this@MainActivity, Manifest.permission.POST_NOTIFICATIONS ) != PackageManager.PERMISSION_GRANTED ) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, // grantResults: IntArray) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return@with } // notificationId is a unique int for each notification that you must define. notify(NOTIFICATION_ID, builder.build()) }
Java
with(NotificationManagerCompat.from(this)) { if (ActivityCompat.checkSelfPermission( this@MainActivity, Manifest.permission.POST_NOTIFICATIONS ) != PackageManager.PERMISSION_GRANTED ) { // TODO: Consider calling // ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding // public void onRequestPermissionsResult(int requestCode, String[] permissions, // int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return } // notificationId is a unique int for each notification that you must define. notify(NOTIFICATION_ID, builder.build()) }
保存您传递给 NotificationManagerCompat.notify()
的通知 ID,因为当您想要更新或移除通知时需要它。
此外,要在运行 Android 13 及更高版本的设备上测试基本通知,请手动开启通知或创建对话框以请求通知。
添加操作按钮
通知最多可提供三个操作按钮,让用户快速响应,例如推迟提醒或回复短信。但这些操作按钮不得重复用户点按通知时执行的操作。
图 3. 包含一个操作按钮的通知。
要添加操作按钮,请将 PendingIntent
传递给 addAction()
方法。这类似于设置通知的默认点按操作,但不同的是,您无需启动 Activity,而是可以执行其他操作,例如启动 BroadcastReceiver
在后台执行任务,这样操作就不会中断已打开的应用。
例如,以下代码展示了如何向特定接收器发送广播
Kotlin
val ACTION_SNOOZE = "snooze" val snoozeIntent = Intent(this, MyBroadcastReceiver::class.java).apply { action = ACTION_SNOOZE putExtra(EXTRA_NOTIFICATION_ID, 0) } val snoozePendingIntent: PendingIntent = PendingIntent.getBroadcast(this, 0, snoozeIntent, 0) val builder = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("My notification") .setContentText("Hello World!") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent) .addAction(R.drawable.ic_snooze, getString(R.string.snooze), snoozePendingIntent)
Java
String ACTION_SNOOZE = "snooze" Intent snoozeIntent = new Intent(this, MyBroadcastReceiver.class); snoozeIntent.setAction(ACTION_SNOOZE); snoozeIntent.putExtra(EXTRA_NOTIFICATION_ID, 0); PendingIntent snoozePendingIntent = PendingIntent.getBroadcast(this, 0, snoozeIntent, 0); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("My notification") .setContentText("Hello World!") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setContentIntent(pendingIntent) .addAction(R.drawable.ic_snooze, getString(R.string.snooze), snoozePendingIntent);
有关构建 BroadcastReceiver
以运行后台工作的更多信息,请参阅广播概览。
如果您正在尝试构建包含媒体播放按钮(例如暂停和跳过曲目)的通知,请参阅如何创建具有媒体控制项的通知。
添加直接回复操作
直接回复操作是在 Android 7.0(API 级别 24)中引入的,它允许用户直接在通知中输入文本。然后将文本传递给您的应用,而无需打开 Activity。例如,您可以使用直接回复操作允许用户在通知中回复短信或更新任务列表。
图 4. 点按“回复”按钮会打开文本输入。
直接回复操作在通知中显示为一个附加按钮,可打开文本输入。当用户完成输入后,系统会将文本回复附加到您为通知操作指定的 intent 中,并将 intent 发送到您的应用。
添加回复按钮
要创建支持直接回复的通知操作,请按照以下步骤操作
- 创建
RemoteInput.Builder
的实例,您可以将其添加到通知操作中。此类构造函数接受一个字符串,系统会将其用作文本输入的键。您的应用稍后会使用该键来检索输入文本。Kotlin
// Key for the string that's delivered in the action's intent. private val KEY_TEXT_REPLY = "key_text_reply" var replyLabel: String = resources.getString(R.string.reply_label) var remoteInput: RemoteInput = RemoteInput.Builder(KEY_TEXT_REPLY).run { setLabel(replyLabel) build() }
Java
// Key for the string that's delivered in the action's intent. private static final String KEY_TEXT_REPLY = "key_text_reply"; String replyLabel = getResources().getString(R.string.reply_label); RemoteInput remoteInput = new RemoteInput.Builder(KEY_TEXT_REPLY) .setLabel(replyLabel) .build();
- 为回复操作创建
PendingIntent
。Kotlin
// Build a PendingIntent for the reply action to trigger. var replyPendingIntent: PendingIntent = PendingIntent.getBroadcast(applicationContext, conversation.getConversationId(), getMessageReplyIntent(conversation.getConversationId()), PendingIntent.FLAG_UPDATE_CURRENT)
Java
// Build a PendingIntent for the reply action to trigger. PendingIntent replyPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), conversation.getConversationId(), getMessageReplyIntent(conversation.getConversationId()), PendingIntent.FLAG_UPDATE_CURRENT);
- 使用
addRemoteInput()
将RemoteInput
对象附加到操作。Kotlin
// Create the reply action and add the remote input. var action: NotificationCompat.Action = NotificationCompat.Action.Builder(R.drawable.ic_reply_icon, getString(R.string.label), replyPendingIntent) .addRemoteInput(remoteInput) .build()
Java
// Create the reply action and add the remote input. NotificationCompat.Action action = new NotificationCompat.Action.Builder(R.drawable.ic_reply_icon, getString(R.string.label), replyPendingIntent) .addRemoteInput(remoteInput) .build();
- 将操作应用到通知并发布通知。
Kotlin
// Build the notification and add the action. val newMessageNotification = Notification.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_message) .setContentTitle(getString(R.string.title)) .setContentText(getString(R.string.content)) .addAction(action) .build() // Issue the notification. with(NotificationManagerCompat.from(this)) { notificationManager.notify(notificationId, newMessageNotification) }
Java
// Build the notification and add the action. Notification newMessageNotification = new Notification.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_message) .setContentTitle(getString(R.string.title)) .setContentText(getString(R.string.content)) .addAction(action) .build(); // Issue the notification. NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.notify(notificationId, newMessageNotification);
当用户触发通知操作时,系统会提示用户输入回复,如图 4 所示。
从回复中检索用户输入
要接收通知回复界面的用户输入,请调用 RemoteInput.getResultsFromIntent()
,并将 BroadcastReceiver
接收到的 Intent
传递给它
Kotlin
private fun getMessageText(intent: Intent): CharSequence? { return RemoteInput.getResultsFromIntent(intent)?.getCharSequence(KEY_TEXT_REPLY) }
Java
private CharSequence getMessageText(Intent intent) { Bundle remoteInput = RemoteInput.getResultsFromIntent(intent); if (remoteInput != null) { return remoteInput.getCharSequence(KEY_TEXT_REPLY); } return null; }
处理完文本后,如果使用了相同的 ID 和标签,请通过调用 NotificationManagerCompat.notify()
更新通知。这是隐藏直接回复界面并向用户确认其回复已正确接收和处理所必需的。
Kotlin
// Build a new notification, which informs the user that the system // handled their interaction with the previous notification. val repliedNotification = Notification.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_message) .setContentText(getString(R.string.replied)) .build() // Issue the new notification. NotificationManagerCompat.from(this).apply { notificationManager.notify(notificationId, repliedNotification) }
Java
// Build a new notification, which informs the user that the system // handled their interaction with the previous notification. Notification repliedNotification = new Notification.Builder(context, CHANNEL_ID) .setSmallIcon(R.drawable.ic_message) .setContentText(getString(R.string.replied)) .build(); // Issue the new notification. NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.notify(notificationId, repliedNotification);
处理此新通知时,使用传递给接收器 onReceive()
方法的上下文。
通过调用 setRemoteInputHistory()
将回复附加到通知底部。但是,如果您正在构建消息应用,请创建消息风格通知,并将新消息附加到对话中。
有关消息应用通知的更多建议,请参阅关于消息应用最佳实践的部分。
添加进度条
通知可以包含一个动画进度指示器,向用户显示正在进行的操作的状态。
图 5. 操作期间的进度条。
如果您可以随时估计操作的完成程度,请使用指示器的“确定性”形式(如图 5 所示),方法是调用 setProgress(max, progress, false)
。第一个参数是“完成”值,例如 100。第二个参数是完成程度。最后一个参数表示这是一个确定性进度条。
随着操作的进行,不断调用 setProgress(max, progress, false)
,其中 progress
为更新后的值,并重新发布通知,如下例所示。
Kotlin
val builder = NotificationCompat.Builder(this, CHANNEL_ID).apply { setContentTitle("Picture Download") setContentText("Download in progress") setSmallIcon(R.drawable.ic_notification) setPriority(NotificationCompat.PRIORITY_LOW) } val PROGRESS_MAX = 100 val PROGRESS_CURRENT = 0 NotificationManagerCompat.from(this).apply { // Issue the initial notification with zero progress. builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false) notify(notificationId, builder.build()) // Do the job that tracks the progress here. // Usually, this is in a worker thread. // To show progress, update PROGRESS_CURRENT and update the notification with: // builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false); // notificationManager.notify(notificationId, builder.build()); // When done, update the notification once more to remove the progress bar. builder.setContentText("Download complete") .setProgress(0, 0, false) notify(notificationId, builder.build()) }
Java
... NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID); builder.setContentTitle("Picture Download") .setContentText("Download in progress") .setSmallIcon(R.drawable.ic_notification) .setPriority(NotificationCompat.PRIORITY_LOW); // Issue the initial notification with zero progress. int PROGRESS_MAX = 100; int PROGRESS_CURRENT = 0; builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false); notificationManager.notify(notificationId, builder.build()); // Do the job that tracks the progress here. // Usually, this is in a worker thread. // To show progress, update PROGRESS_CURRENT and update the notification with: // builder.setProgress(PROGRESS_MAX, PROGRESS_CURRENT, false); // notificationManager.notify(notificationId, builder.build()); // When done, update the notification once more to remove the progress bar. builder.setContentText("Download complete") .setProgress(0,0,false); notificationManager.notify(notificationId, builder.build());
操作结束时,progress
必须等于 max
。您可以保留进度条以显示操作已完成,或将其移除。无论哪种情况,都要更新通知文本以显示操作已完成。要移除进度条,请调用 setProgress(0, 0, false)
。
要显示不确定性进度条(不指示完成百分比的条),请调用 setProgress(0, 0, true)
。结果是一个指示器,其样式与前面的进度条相同,但它是连续动画,不指示完成。进度动画会一直运行,直到您调用 setProgress(0, 0, false)
并更新通知以移除活动指示器为止。
记住更改通知文本以指示操作已完成。
设置系统范围类别
当用户启用勿扰模式时,Android 会使用预定义的系统范围类别来确定是否通过特定通知打扰用户。
如果您的通知属于 NotificationCompat
中定义的通知类别之一(例如 CATEGORY_ALARM
、CATEGORY_REMINDER
、CATEGORY_EVENT
或 CATEGORY_CALL
),请通过将适当的类别传递给 setCategory()
来声明它
Kotlin
var builder = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("My notification") .setContentText("Hello World!") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setCategory(NotificationCompat.CATEGORY_MESSAGE)
Java
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("My notification") .setContentText("Hello World!") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setCategory(NotificationCompat.CATEGORY_MESSAGE);
系统会使用有关您通知类别的此信息来决定设备处于勿扰模式时是否显示您的通知。但是,您无需设置系统范围类别。仅当您的通知与 NotificationCompat
中定义的类别之一匹配时才这样做。
显示紧急消息
您的应用可能需要显示紧急、时效性消息,例如来电或响起的闹钟。在这种情况下,您可以将全屏 intent 与通知关联。
当通知被调用时,用户会看到以下情况之一,具体取决于设备的锁定状态
- 如果用户的设备已锁定,则会显示覆盖锁定屏幕的全屏 Activity。
- 如果用户的设备未锁定,通知会以展开形式显示,其中包含用于处理或关闭通知的选项。
以下代码片段演示了如何将通知与全屏 intent 关联
Kotlin
val fullScreenIntent = Intent(this, ImportantActivity::class.java) val fullScreenPendingIntent = PendingIntent.getActivity(this, 0, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT) var builder = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("My notification") .setContentText("Hello World!") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setFullScreenIntent(fullScreenPendingIntent, true)
Java
Intent fullScreenIntent = new Intent(this, ImportantActivity.class); PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0, fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("My notification") .setContentText("Hello World!") .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setFullScreenIntent(fullScreenPendingIntent, true);
设置锁屏可见性
要控制锁屏通知的详细程度,请调用 setVisibility()
并指定以下值之一
VISIBILITY_PUBLIC
:通知的全部内容显示在锁屏上。VISIBILITY_SECRET
:通知的任何部分都不显示在锁屏上。VISIBILITY_PRIVATE
:只有基本信息(例如通知的图标和内容标题)显示在锁屏上。通知的全部内容不显示。
当您设置 VISIBILITY_PRIVATE
时,您还可以提供通知内容的备用版本,隐藏某些详细信息。例如,短信应用可以显示一个通知,显示“您有 3 条新短信”,但隐藏消息内容和发件人。要提供此备用通知,首先像往常一样使用 NotificationCompat.Builder
创建备用通知。然后,使用 setPublicVersion()
将备用通知附加到普通通知。
请记住,用户始终对通知是否在锁屏上可见拥有最终控制权,并且可以根据您应用的通知渠道进行控制。
更新通知
发布通知后要更新它,请再次调用 NotificationManagerCompat.notify()
,并向其传递之前使用的相同 ID。如果之前的通知已被关闭,则会改为创建新的通知。
您可以选择调用 setOnlyAlertOnce()
,这样您的通知只会第一次出现时打断用户(通过声音、振动或视觉提示),而不会在后续更新时打断。
移除通知
通知保持可见,直到发生以下情况之一
- 用户关闭通知。
- 如果创建通知时调用了
setAutoCancel()
,则用户点按通知。 - 您调用
cancel()
并指定通知 ID。此方法也会删除正在进行的通知。 - 您调用
cancelAll()
,此方法会移除您之前发布的所有通知。 - 如果创建通知时使用
setTimeoutAfter()
设置了超时,则指定的持续时间已过。如果需要,您可以在指定的超时持续时间结束之前取消通知。
消息应用最佳实践
在为消息和聊天应用创建通知时,请考虑此处列出的最佳实践。
使用 MessagingStyle
从 Android 7.0(API 级别 24)开始,Android 提供了一个专用于消息内容的通知样式模板。使用 NotificationCompat.MessagingStyle
类,您可以更改通知上显示的多个标签,包括对话标题、附加消息和通知的内容视图。
以下代码片段演示了如何使用 MessagingStyle
类自定义通知的样式。
Kotlin
val user = Person.Builder() .setIcon(userIcon) .setName(userName) .build() val notification = NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("2 new messages with $sender") .setContentText(subject) .setSmallIcon(R.drawable.new_message) .setStyle(NotificationCompat.MessagingStyle(user) .addMessage(messages[1].getText(), messages[1].getTime(), messages[1].getPerson()) .addMessage(messages[2].getText(), messages[2].getTime(), messages[2].getPerson()) ) .build()
Java
Person user = new Person.Builder() .setIcon(userIcon) .setName(userName) .build(); Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("2 new messages with " + sender) .setContentText(subject) .setSmallIcon(R.drawable.new_message) .setStyle(new NotificationCompat.MessagingStyle(user) .addMessage(messages[1].getText(), messages[1].getTime(), messages[1].getPerson()) .addMessage(messages[2].getText(), messages[2].getTime(), messages[2].getPerson()) ) .build();
从 Android 9.0(API 级别 28)开始,还需要使用 Person
类,以便获得通知及其头像的最佳渲染效果。
使用 NotificationCompat.MessagingStyle
时,请执行以下操作
- 调用
MessagingStyle.setConversationTitle()
为两人以上的群聊设置标题。一个好的对话标题可以是群聊的名称,或者如果没有名称,则可以是对话参与者的列表。如果没有此设置,消息可能会被误认为属于与对话中最近一条消息发送者的一对一对话。 - 使用
MessagingStyle.setData()
方法包含媒体消息,例如图片。支持模式为 image/* 的 MIME 类型。
使用直接回复
直接回复允许用户行内回复消息。
- 用户使用行内回复操作回复后,请使用
MessagingStyle.addMessage()
更新MessagingStyle
通知,并且不要撤回或取消通知。不取消通知允许用户从通知发送多个回复。 - 为了使行内回复操作与 Wear OS 兼容,请调用
Action.WearableExtender.setHintDisplayInlineAction(true)
。 - 使用
addHistoricMessage()
方法通过将历史消息添加到通知中,为直接回复对话提供上下文。
启用智能回复
- 要启用智能回复,请在回复操作上调用
setAllowGeneratedResponses(true)
。这使得当通知桥接到 Wear OS 设备时,用户可以使用智能回复。智能回复是使用NotificationCompat.MessagingStyle
通知提供的上下文,由完全基于手表的机器学习模型生成的,并且不会上传数据到互联网以生成回复。
添加通知元数据
- 分配通知元数据以告知系统在设备处于
勿扰模式
时如何处理您的应用通知。例如,使用addPerson()
或setCategory(Notification.CATEGORY_MESSAGE)
方法来覆盖勿扰模式设置。