javaandroidaudionotifications

Android: Custom notification sound not playing


I've tried pretty much all available answers on the site, but somehow I cannot get the notification sound to work. The current code I'm testing is this (the notification is built in an alarm reciever):

public class AlarmReceiver extends BroadcastReceiver {

private static final int NOTIFICATION_ID = 0;

@Override
public void onReceive(Context context, Intent intent) {


  NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setContentTitle(context.getString(R.string.app_name))
            .setContentIntent(PendingIntent.getActivity(context, 0, new Intent(context, MainActivity_.class), 0))
            .setContentText("temporary text")
            .setAutoCancel(true)
            .setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                    + "://" + context.getPackageName() + "/raw/alert"))
            .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.ic_stat_notification);

    Notification notification = builder.build();
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID, notification);

The sound however, can be played via MediaPlayer, so the format is not the issue here. Could it have to do with the lenght of the sound (30 seconds)? Thank you for your help!


Solution

  • Try changing your .setSound() to this

    .setSound(Uri.parse("android.resource://"
                                + context.getPackageName() + "/"
                                + R.raw.alert))
    

    Hope this will work