How to set notification with custom sound in android

前端 未结 6 1884

I copied the mp3 (kalimba.mp3) file into the raw folder in the res folder. But when the notification is triggered it produces the default sound.

6条回答
  •  粉色の甜心
    2020-11-29 03:29

    I make this static function in HelperClass.java

        public static void givenotification(Context context,String message) {
             NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
    
             Intent notificationIntent = new Intent(context, DesireActivity.class);
             PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
    
             Notification notification = new Notification();
             NotificationCompat.Builder builder;
             builder = new NotificationCompat.Builder(context);
    
             notification = builder.setContentIntent(pendingIntent)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setTicker(context.getString(R.string.app_name)).setWhen(System.currentTimeMillis())
                .setAutoCancel(true).setContentTitle(context.getString(R.string.app_name))
                .setContentText(message).build();
             notification.sound = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.kalimba);
             notificationManager.notify(1, notification);
         }
    

    Then any Activity like in MainActivity HelperClass.givenotification(MainActivity.this,"Your Notification Message"); OR in fragment HelperClass.givenotification(getActivity(),"Your Notification Message");

    Hope this help someone.

提交回复
热议问题