是否需要检查通知渠道是否已经创建?

Kir*_*tov 2 java android push-notification android-notifications kotlin

我们是否需要在创建通知通道之前检查它尚未创建?

 private fun createChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        // todo: add here check if channel is already created
        val defaultChannel = NotificationChannel(MEDIA_UPLOAD_NOTIFICATION_CHANNEL_ID, MEDIA_UPLOAD_NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH)
        defaultChannel.description = MEDIA_UPLOAD_NOTIFICATION_CHANNEL_DESC
        defaultChannel.enableVibration(true)
        notificationManager.createNotificationChannel(defaultChannel)
    }
}
Run Code Online (Sandbox Code Playgroud)

Roh*_*5k2 5

不,你真的不需要检查。如果存在具有相同 ID 的频道,则 Android 不会创建另一个频道。

根据文档

使用其原始值创建现有通知通道不会执行任何操作,因此在启动应用程序时调用此代码是安全的。

更多信息请访问https://developer.android.com/training/notify-user/channels#CreateChannel