Search code examples
androidpush-notificationassets

I want to set Push Notification Sound from Asset Folder ,Android


I have an .mp3 file in asset folder named "error.mp3" . i want set that sound along with the push notification , how can i do that , i have tried this code to do that

 Uri sound = Uri.parse("file:///android_asset/error.mp3");
 mBuilder.setSound(sound);

but its not working, when i use the default notification sound , it's working. i need some help...

This is my BroadcastReceiver class

public class Notificationmassage extends BroadcastReceiver {


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


    showNotification(context);

}

private void showNotification(Context context) {
    Log.i("notification", "visible");



    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
            new Intent(context, MainActivity.class), 0);

    NotificationCompat.Builder mBuilder =
            (NotificationCompat.Builder) new NotificationCompat.Builder(context)
                    .setSmallIcon(R.drawable.ic)
                    .setContentTitle("Radio Planet")
                    .setContentText("Explore music");
    mBuilder.setContentIntent(contentIntent);


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


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



   Uri sound = Uri.parse("file:///android_asset/error.mp3");
   mBuilder.setSound(sound);

    mBuilder.setAutoCancel(true);
    NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    mNotificationManager.notify(2, mBuilder.build());


}
}

Solution

  • Please try to put your .mp3 files in raw folder instead of assets, sometimes it's not working so please use like this

    Uri path = Uri.parse("android.resource://com.example.test/" + R.raw.sample);
    

    com.example.test // replace this with your package name

    and then set

    mBuilder.setSound(path);
    

    Folder Structure

    res/raw/test.mp3
    

    Hope it will work for you. Enjoy Programming.

    enter image description here

    enter image description here