Android notification setSound is not working

淺唱寂寞╮ 提交于 2019-12-03 05:16:42

below code will help you:

String CHANNEL_ID="1234";

Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"+ getApplicationContext().getPackageName() + "/" + R.raw.mysound);

NotificationManager mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);

For API 26+ you need to put some additional code like below:

NotificationChannel mChannel;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(CHANNEL_ID, Utils.CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            mChannel.setLightColor(Color.GRAY);
            mChannel.enableLights(true);
            mChannel.setDescription(Utils.CHANNEL_SIREN_DESCRIPTION);
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_NOTIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build();
            mChannel.setSound(soundUri, audioAttributes);

            if (mNotificationManager != null) {
                mNotificationManager.createNotificationChannel( mChannel );
            }
    }

General code:

 NotificationCompat.Builder status = new NotificationCompat.Builder(getApplicationContext(),CHANNEL_ID);     
                      status.setAutoCancel(true)
                            .setWhen(System.currentTimeMillis())
                            .setSmallIcon(R.drawable.logo)
                            //.setOnlyAlertOnce(true)
                            .setContentTitle(getString(R.string.app_name))
                            .setContentText(messageBody)
                            .setVibrate(new long[]{0, 500, 1000})
                            .setDefaults(Notification.DEFAULT_LIGHTS )
                            .setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE+ "://" +mContext.getPackageName()+"/"+R.raw.apple_ring))
                            .setContentIntent(pendingIntent)
                            .setContent(views);

                    mNotificationManager.notify(major_id, status.build());

where mysound is my ringtone which is put under res/raw folder.

Note: you have to only put name of ringtone without extension like raw/mysound

For API 26+ you need to set the sound on the notification channel:

Uri soundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"+ getApplicationContext().getPackageName() + "/" + R.raw.siren);
NotificationManager mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    NotificationChannel mChannel;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(Utils.CHANNEL_SIREN_ID, Utils.CHANNEL_SIREN_NAME, NotificationManager.IMPORTANCE_HIGH);
            mChannel.setLightColor(Color.GRAY);
            mChannel.enableLights(true);
            mChannel.setDescription(Utils.CHANNEL_SIREN_DESCRIPTION);
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build();
            mChannel.setSound(soundUri, audioAttributes);

            if (mNotificationManager != null) {
                mNotificationManager.createNotificationChannel( mChannel );
            }
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, Utils.CHANNEL_SIREN_ID)
            .setSmallIcon(R.drawable.ic_stat_maps_local_library)
            .setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), R.mipmap.ic_launcher))
            .setTicker(title)
            .setContentTitle(contentTitle)
            .setContentText(contentText)
            .setAutoCancel(true)
            .setLights(0xff0000ff, 300, 1000) // blue color
            .setWhen(System.currentTimeMillis())
            .setPriority(NotificationCompat.PRIORITY_DEFAULT);

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            mBuilder.setSound(soundUri);
    }

    int NOTIFICATION_ID = 1; // Causes to update the same notification over and over again.
    if (mNotificationManager != null) {
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }
  1. Try clearing data (or fresh install)
  2. Trying this again

The settings are set the first time you create the channel and then not modified unless you do it manually by fresh install or clearing data.

For more info on this read the top answer here: Android Oreo notification keep making Sound even if I do not set sound. On Older version, works perfectly

you can call this method while handling notification

    public void playNotificationSound() {
    try {
        Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                + "://" + mContext.getPackageName() + "/raw/notification");
        Ringtone r = RingtoneManager.getRingtone(mContext, alarmSound);
        r.play();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Use this for setting sound

Uri defaultSoundUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://" + mContext.getPackageName() + "/raw/mysound");


NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(mContext)
                        .setContentIntent(mainPIntent)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.ic_launcher))
                        .setContentTitle("" + title)
                        .setAutoCancel(true)
                        .setSound(defaultSoundUri)
                        .setContentText("" + body);

        NotificationManager mNotificationManager =
                (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(title, NOTIFICATION_ID, mBuilder.build());

You are accessing the sound in a subfolder in the resources

change the source of your uri to

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

For the default sound, use:

notification.defaults |= Notification.DEFAULT_SOUND;

I am not sure but i think issue is that you are doing the wrong way "/raw/mysound.mp3 :

Uri uri = Uri.parse("android.resource://" + ctxt.getPackageName() + "/raw/mysound.mp3");

First add the permission in manifest : uses-permission android:name="android.permission.VIBRATE" /> then you can set the default sound like :-

Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);

and for vibration:

mBuilder.setVibrate(new long[] { 1000, 1000});

for custom sound, put mp3 file on this path:Res\raw\sound.mp3 and then

Notification notification = builder.build();
 notification.sound = Uri.parse("android.resource://"
        + context.getPackageName() + "/" + R.raw.sound);
 Notification.Builder builder = new Notification.Builder(context);
    builder.setContentTitle(mTitle);
    builder.setContentText(mContentText);
    builder.setSmallIcon(R.mipmap.ic_launcher);

    builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
    builder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
    builder.setDefaults(Notification.DEFAULT_ALL);

Use this to work with sound, I hope it will solve your problem, Cheers!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!