1

I'm developing android application which send notification for user and I want to set custom sound for this notification. It works well for android version less than android 8. but sound doesn't play for android 8 and higher, so what is the problem ? this is notification code

Uri sound = Uri.parse("android.resource://"
                + context.getPackageName() + "/" + R.raw.sound);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelID, "my app",
                    NotificationManager.IMPORTANCE_DEFAULT);
            AudioAttributes attributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build();
            channel.setSound(sound, attributes);
            NotificationManager manager = context.getSystemService(NotificationManager.class);
            manager.createNotificationChannel(channel);
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channelID);
        builder.setSmallIcon(R.drawable.ic_notify)
                .setContentTitle(title)
                .setContentText(message)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setOngoing(true)
                .setSound(sound)
                .setAutoCancel(true);

        Intent intent = new Intent(context, acticity);
        intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
        PendingIntent pi = PendingIntent.getActivity(context, 99,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(pi);

        NotificationManagerCompat mcompact = NotificationManagerCompat.from(context);

        mcompact.notify(99, builder.build());

1 Answers1

0

Why don't you try this code:

// Creating an Audio Attribute
AudioAttributes audioAttributes = new AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                .setUsage(AudioAttributes.USAGE_ALARM)
                .build();

// Creating Channel
NotificationChannel notificationChannel = new NotificationChannel(context.getString(R.string.channel_id_prayers),context.getString(R.string.channel_name_prayers),NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setSound(sound,audioAttributes);
Sambhav Khandelwal
  • 3,585
  • 2
  • 7
  • 38