0

I am sending data messages from our app server calling firebase api to users.Users are receiving the notifications but sound is not playing when notification arrives.

here is the code

public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    sendNotification(remoteMessage); 
}

private void sendNotification(RemoteMessage message) {
    Intent intent;
    intent = new Intent(this, HomeActivity.class);
    Log.d(TAG, message.getData().toString());

    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Ringtone r = RingtoneManager.getRingtone(this, defaultSoundUri);
    r.play();

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(message.getData().get("title"))
            .setContentText(Html.fromHtml(message.getData().get("body")))
            .setAutoCancel(true)
//                .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notificationBuilder.build());
        saveMessage(message);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

what could be the problem???

AL.
  • 36,815
  • 10
  • 142
  • 281
JakeGosemath
  • 87
  • 1
  • 1
  • 10
  • you can check for your solution in this link :https://stackoverflow.com/questions/37959588/no-notification-sound-when-sending-notification-from-firebase-in-android?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – Apurva Geete Jun 08 '18 at 07:22
  • this means i need to send the parameter "sound" :"default or custom" in the data message sent to the user. – JakeGosemath Jun 08 '18 at 07:30
  • Have you tried setting the defaults? i.e. `setDefaults(Notification.DEFAULT_SOUND)`? – AL. Jun 08 '18 at 19:54

1 Answers1

0

You need to set sound on notification builder. So, Try with uncomment below line.

.setSound(defaultSoundUri)

and comment below lines.

//Ringtone r = RingtoneManager.getRingtone(this, defaultSoundUri);
//r.play(); 

If you want to play notification sound when app is in background, you need to add the sound parameter to the notification payload.

Supports "default" or the filename of a sound resource bundled in the app. Sound files must reside in /res/raw/

Priyank Patel
  • 12,244
  • 8
  • 65
  • 85