顯示具時效性的通知

應用程式可能需要在特定情況下 (例如正在執行的鬧鐘或來電) 緊急吸引使用者的注意。如果應用程式指定搭載 Android 9 (API 級別 28) 以下版本的裝置,您可以在應用程式於背景執行時啟動活動,處理這種情況。本文說明如何在搭載 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)
    }
}

使用者首次執行應用程式時,會在應用程式的「App info」(應用程式資訊) 系統畫面看到圖 1 之類的內容:

顯示您應用程式「應用程式資訊」和「通知」畫面的圖片。
圖 1. 應用程式系統設定的「App Info」(應用程式資訊) 畫面中的通知區段。

管理通知權限

從 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 所示的對話方塊:

顯示權限要求對話方塊的圖片
圖 2. 通知權限要求的系統對話方塊。

如果使用者接受權限要求,應用程式的「App info」(應用程式資訊) 部分如圖 3 所示:

顯示已授予通知權限要求後「應用程式資訊」畫面的圖片
圖 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 所示:

顯示高優先順序通知的圖片
圖 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);