androidkotlinnotification-channel

NotificationChannel setSound and vibration not working


I have a problem to play sound, when notification will come, notification is showing, but there is no sound or vibration, I saw many question and answers to how to set the sound and vibration to notificaiton channels, but it doesn't works, this is how I'm trying that

val pattern = longArrayOf(0, 200, 60, 200)
val chatSound = Uri.parse("${ContentResolver.SCHEME_ANDROID_RESOURCE}://" + context.packageName + "/" + R.raw.chat_alert)
val mBuilder = NotificationCompat.Builder(context, CHANNEL_ID)
  .setSmallIcon(R.mipmap.ic_launcher)
  .setContentTitle(title)
  .setContentText(body)
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

val notification = mBuilder.build()

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
  val mChanel = NotificationChannel(CHANNEL_ID, "test", NotificationManager.IMPORTANCE_HIGH)
  val audioAttributes = AudioAttributes.Builder()
    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
    .build()
  mChanel.setSound(chatSound, audioAttributes)
  mChanel.enableVibration(true)
  mChanel.enableLights(true)
  mChanel.vibrationPattern = pattern
  mNotificationManager.createNotificationChannel(mChanel)
}
mNotificationManager.notify(i, notification)

I'm testing it for Android Pie

targetSdkVersion 28

Solution

  • Seems when notification channel is created at first time then it doesn't automatically update if something where changed, like in my case, at first, I ran notification channel without sound and vibration.

    Solution: Clear app data or just uninstall the app, after that it worked properly