欢迎参加我们将于 6 月 3 日举行的 #Android11:Beta 版发布会

显示有时效性的通知

在特定情况下,您的应用可能需要立即引起用户的注意,例如闹钟正在响铃或有来电时。您以前可能已出于此目的配置了应用,也就是当应用在后台运行时启动 Activity。

要在运行 Android 10(API 级别 29)或更高版本的设备上提供类似的行为,请完成本指南中描述的步骤。

创建高优先级通知

创建通知时,请务必添加描述性标题和消息。您还可以选择提供全屏 intent

以下代码段中显示了示例通知:

Kotlin

    val fullScreenIntent = Intent(this, CallActivity::class.java)
    val fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
        fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT)

    val notificationBuilder =
            NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("Incoming call")
        .setContentText("(919) 555-1234")
        .setPriority(NotificationCompat.PRIORITY_HIGH)
        .setCategory(NotificationCompat.CATEGORY_CALL)

        // Use a full-screen intent only for the highest-priority alerts where you
        // have an associated activity that you would like to launch after the user
        // interacts with the notification. Also, if your app targets Android 10
        // or higher, you need to request the USE_FULL_SCREEN_INTENT permission in
        // order for the platform to invoke this notification.
        .setFullScreenIntent(fullScreenPendingIntent, true)

    val incomingCallNotification = notificationBuilder.build()
    

Java

    Intent fullScreenIntent = new Intent(this, CallActivity.class);
    PendingIntent fullScreenPendingIntent = PendingIntent.getActivity(this, 0,
            fullScreenIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder notificationBuilder =
            new NotificationCompat.Builder(this, CHANNEL_ID)
        .setSmallIcon(R.drawable.notification_icon)
        .setContentTitle("Incoming call")
        .setContentText("(919) 555-1234")
        .setPriority(NotificationCompat.PRIORITY_HIGH)
        .setCategory(NotificationCompat.CATEGORY_CALL)

        // Use a full-screen intent only for the highest-priority alerts where you
        // have an associated activity that you would like to launch after the user
        // interacts with the notification. Also, if your app targets Android 10
        // or higher, you need to request the USE_FULL_SCREEN_INTENT permission in
        // order for the platform to invoke this notification.
        .setFullScreenIntent(fullScreenPendingIntent, true);

    Notification incomingCallNotification = notificationBuilder.build();
    

向用户显示通知

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

如果您的通知正在进行(例如来电),请将该通知与前台服务相关联。以下代码段展示了如何显示与前台服务关联的通知:

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);