显示时间敏感通知

在某些情况下,例如闹钟响铃或有来电时,您的应用可能需要紧急引起用户的注意。对于以运行 Android 9 (API 级别 28) 或更低版本的设备为目标平台的应用,您可以通过在应用位于后台时启动 Activity 来处理此问题。本文档介绍了如何在运行 Android 10 (API 级别 29) 到 Android 13 (API 级别 33) 的设备上实现此行为。

添加 POST_NOTIFICATIONS 权限

从 Android 13 开始,将以下行添加到您的 AndroidManifest.xml 文件中

<manifest ...>
    <uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>
    <application ...>
        ...
    </application>
</manifest>

添加此权限后,您可以创建通知渠道。

创建通知渠道

创建通知渠道以正确显示您的通知,并让用户在应用设置中管理通知。有关通知渠道的更多信息,请参阅创建和管理通知渠道

在您的 Application 类的 onCreate 方法中创建您的通知渠道

Kotlin

class DACapp : Application() {
    override fun onCreate() {
        super.onCreate()
        val channel = NotificationChannel(
            CHANNEL_ID,
            "High priority notifications",
            NotificationManager.IMPORTANCE_HIGH
        )

        val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(channel)
    }
}

当用户首次运行您的应用时,会在应用的应用信息系统屏幕中看到类似图 1 的内容

An image showing the App Info, Notification screen of your app.
图 1. 应用系统设置中应用信息屏幕的“通知”部分。

管理通知权限

从 Android 13 开始,在向用户显示通知之前请求通知权限。

最小实现如下所示

Kotlin

val permissionLauncher = rememberLauncherForActivityResult(
    contract = ActivityResultContracts.RequestPermission(),
    onResult = { hasNotificationPermission = it }
)
...
Button(
    onClick = {
        if (!hasNotificationPermission) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                permissionLauncher.launch(Manifest.permission.POST_NOTIFICATIONS)
            }
        }
    },
) {
    Text(text = "Request permission")
}

如果您的设备运行的是 Android 13,点击 Request permission 按钮将触发如图 2 所示的对话框

An image showing the permission request dialog
图 2. 通知权限请求的系统对话框。

如果用户接受了权限请求,则应用的应用信息部分会显示如图 3 所示的内容

An image showing the App Info screen after granted notification permission request
图 3. 通知权限已授予。

创建高优先级通知

创建通知时,包含描述性标题和消息。

以下示例包含一条通知

Kotlin

private fun showNotification() {
    val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

    val notificationBuilder =
        NotificationCompat.Builder(this, CHANNEL_ID)
            .setSmallIcon(R.drawable.baseline_auto_awesome_24)
            .setContentTitle("HIGH PRIORITY")
            .setContentText("Check this dog puppy video NOW!")
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_RECOMMENDATION)

    notificationManager.notify(666, notificationBuilder.build())
}

向用户显示通知

调用 showNotification() 函数会触发通知,如下所示

Kotlin

Button(onClick = { showNotification() }) {
    Text(text = "Show notification")
}

此示例中的通知如图 4 所示

An image showing a high priority notification
图 4. 高优先级通知。

持续通知

当您向用户显示通知时,他们可以确认或关闭您的应用提醒。例如,用户可以接受或拒绝来电。

如果您的通知是持续通知,例如来电,请将通知与前台服务相关联。以下代码片段展示了如何显示与前台服务相关联的通知

Kotlin

// Provide a unique integer for the "notificationId" of each notification.
startForeground(notificationId, notification)

Java

// Provide a unique integer for the "notificationId" of each notification.
startForeground(notificationId, notification);