简体   繁体   中英

Android notification sound is not working

I have my own BroadcastReceiver which sends push notifications. I need to provide sound for notifications in my application. Here's a code that I have right now:

public class TimeReceiver extends BroadcastReceiver {

   @Override
   public void onReceive(Context context, Intent intent) {
      Log.d("tag", "onReceive");
      sendNotification(context);;
}

   private void sendNotification(Context context) {
      NotificationCompat.Builder builder = createBuilder(context);
      Notification notification = builder.build();
      notification.defaults |= Notification.DEFAULT_SOUND;
      getNotificationManager(context).notify(1, builder.build());
   }

   private NotificationManager getNotificationManager(Context context) {
      return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
   }

   private NotificationCompat.Builder createBuilder(Context context) {
      NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_keyboard_arrow_right_black_24dp)
            .setContentTitle(context.getResources().getString(R.string.title))
            .setContentText(context.getResources().getString(R.string.content))
            .setAutoCancel(true);
      return builder;
   }
}

Receiver works and send notifications, but there's no sound. I also tried setSound(uri) for NotificationCompat.Builder and it also was not work. What am I doing wrong?

Change this line-

getNotificationManager(context).notify(1, builder.build())

to -

getNotificationManager(context).notify(1, notification). 

You are passing the old notification object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM