105

I am sending push notification from firebase to my Android Application. but when my app is in background firebase onMessageReceived method is not called instead firebase send notification to system for showing notification in system tray. notification appears in system tray but no sound for notification even i have allowed notification sound for my app in system settings.

what I can do to play notification sound when notification received from firebase.

This is how I am sending notification from firebase to my app Blogpost link.

How to Add firebase in your Android Application

Developine
  • 12,483
  • 8
  • 38
  • 42

10 Answers10

124

In the notification payload of the notification there is a sound key.

From the official documentation its use is:

Indicates a sound to play when the device receives a notification. Supports default or the filename of a sound resource bundled in the app. Sound files must reside in /res/raw/.

Eg:

{
    "to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",

    "notification" : {
      "body" : "great match!",
      "title" : "Portugal vs. Denmark",
      "icon" : "myicon",
      "sound" : "mySound"
    }
  }

If you want to use default sound of the device, you should use: "sound": "default".

See this link for all possible keys in the payloads: https://firebase.google.com/docs/cloud-messaging/http-server-ref#notification-payload-support

For those who don't know firebase handles notifications differently when the app is in background. In this case the onMessageReceived function is not called.

When your app is in the background, Android directs notification messages to the system tray. A user tap on the notification opens the app launcher by default. This includes messages that contain both notification and data payload. In these cases, the notification is delivered to the device's system tray, and the data payload is delivered in the extras of the intent of your launcher Activity.

whlk
  • 15,487
  • 13
  • 66
  • 96
Isj
  • 2,020
  • 1
  • 14
  • 20
  • 29
    if you want to use default sound of device, you should use: "sound" : "default" – Brian Vo Sep 01 '16 at 09:33
  • @TranVo thanks for points out that "default" value plays the default sound of the device, you saved me a lot of time! – Mattia Ruggiero Nov 21 '16 at 10:12
  • in the notification am getting response for which screen redirect key if app in foreground and click notification working fine if in backgroung notification clicked open launcher activity onMessageReceived how to handle please help me for both background and foreground handlings – Harsha Nov 22 '16 at 12:39
  • 1
    I tried all the possible ways but not able have that default sound or sound from setting my own tone and also not getting vibration what may be the reason – santhosh Jan 24 '17 at 11:08
  • I have done .setSound(defaultSoundUri), but I am not getting notification sound, when send from firebase – Umashankar B Mar 13 '17 at 06:28
  • 2
    So how can I disable the sound of the notification? – iamatsundere181 Jul 27 '18 at 03:54
  • I assume not including the sound parameter should do it, but please verify – Isj Jul 27 '18 at 19:26
  • This won't work with the new APIs. ```Error: Invalid JSON payload received. Unknown name "badge" at 'message.notification': Cannot find field.``` Also you're using TypeScript (you should be) it will flag this on compilation before you submit it to Firebase – Oliver Dixon Jan 07 '19 at 17:35
  • any way to disable the notification sound? Excluding the sound attribute doesn't work, the sound is still enabled – Dan Dinu Jul 16 '19 at 17:46
  • I have the sound but no vibration, any idea? – TPG Aug 28 '19 at 06:40
  • 2
    Has the new Notification Channel system obsoleted this API for older devices, or does it still work for older devices? I've been trying to make custom sounds show up for a Nougat device but I just seem to get the default chime sound effect no matter what I enter in "sound" or "soundName." I've tried "mysoundeffect.wav" and "mysoundeffect" with no luck. – John Gorenfeld Jun 18 '20 at 10:36
  • I want a feature in app where user can disable all notifications sound. But how can I achieve this. Because if sound is ON in first time then how can we disable it on notification when app is in terminated state. – Muhammad Umair Saqib Jul 13 '22 at 13:28
31

Try this

{
    "to" : "DEVICE-TOKEN",

    "notification" : {
      "body"  : "NOTIFICATION BODY",
      "title" : "NOTIFICATION TITILE",
      "sound" : "default"
    }
  }

@note for custom notification sound:-> "sound" : "MyCustomeSound.wav"

Sam
  • 464
  • 4
  • 14
  • 3
    So where do you put that file? in raw? assets? – Hamzeh Soboh Dec 26 '17 at 07:14
  • 3
    Not assets folder, create a newfolder under res, call it raw. Then copy and paste your wav or mp3 file to that folder. @HamzehSoboh – Ally Makongo Apr 17 '18 at 23:10
  • 2
    I put sound into /res/raw/my_sound.mp3 in the Android app then call API with "sound": "my_sound.mp3". Not working, just default sound was played :( Anyone like me ? – The Anh Nguyen Dec 24 '20 at 07:34
  • Oh, I make it worked. Using Android Notification Channel, More detail here: https://stackoverflow.com/questions/61142155/custom-sound-in-firebase-push-notification – The Anh Nguyen Dec 24 '20 at 08:26
28

adavaced options select advanced options when Write a message, and choose sound activated choose activated

this is My solution

KongJing
  • 475
  • 5
  • 7
  • @KongJing in Android 8 and above, it always have sound no matter setting of Firebase console. Do you know a way to prevent sound completely? – Phong Nguyen May 24 '19 at 02:49
  • I am sorry to see this so late, I can't solve this problem.@Think Twice Code Once – KongJing Aug 21 '19 at 09:54
15

The onMessageReceived method is fired only when app is in foreground or the notification payload only contains the data type.

From the Firebase docs

For downstream messaging, FCM provides two types of payload: notification and data.

For notification type, FCM automatically displays the message to end-user devices on behalf of the client app. Notifications have a predefined set of user-visible keys.
For data type, client app is responsible for processing data messages. Data messages have only custom key-value pairs.

Use notifications when you want FCM to handle displaying a notification on your client app's behalf. Use data messages when you want your app to handle the display or process the messages on your Android client app, or if you want to send messages to iOS devices when there is a direct FCM connection.

Further down the docs

App behaviour when receiving messages that include both notification and data payloads depends on whether the app is in the background or the foreground—essentially, whether or not it is active at the time of receipt.
When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.
When in the foreground, your app receives a message object with both payloads available.

If you are using the firebase console to send notifications, the payload will always contain the notification type. You have to use the Firebase API to send the notification with only the data type in the notification payload. That way your app is always notified when a new notification is received and the app can handle the notification payload.

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

Renjith
  • 5,783
  • 9
  • 31
  • 42
11

I was also having a problem with notifications that had to emit sound, when the app was in foreground everything worked correctly, however when the app was in the background the sound just didn't come out.

The notification was sent by the server through FCM, that is, the server mounted the JSON of the notification and sent it to FCM, which then sends the notification to the apps. Even if I put the sound tag, the sound does not come out in the backgound.

enter image description here

Even putting the sound tag it didn't work.

enter image description here

After so much searching I found the solution on a github forum. I then noticed that there were two problems in my case:

1 - It was missing to send the channel_id tag, important to work in API level 26+

enter image description here

2 - In the Android application, for this specific case where notifications were being sent directly from the server, I had to configure the channel id in advance, so in my main Activity I had to configure the channel so that Android knew what to do when notification arrived.

In JSON sent by the server:

   {
  "title": string,
  "body": string,
  "icon": string,
  "color": string,
  "sound": mysound,

  "channel_id": videocall,
  //More stuff here ...
 }

In your main Activity:

 @Background
    void createChannel(){
            Uri sound = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.app_note_call);
            NotificationChannel mChannel;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                mChannel = new NotificationChannel("videocall", "VIDEO CALL", NotificationManager.IMPORTANCE_HIGH);
                mChannel.setLightColor(Color.GRAY);
                mChannel.enableLights(true);
                mChannel.setDescription("VIDEO CALL");
                AudioAttributes audioAttributes = new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .setUsage(AudioAttributes.USAGE_ALARM)
                        .build();
                mChannel.setSound(sound, audioAttributes);

                NotificationManager notificationManager =
                        (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
                notificationManager.createNotificationChannel(mChannel);
            }
    }

This finally solved my problem, I hope it helps someone not to waste 2 days like I did. I don't know if it is necessary for everything I put in the code, but this is the way. I also didn't find the github forum link to credit the answer anymore, because what I did was the same one that was posted there.

Rafael Rocha
  • 285
  • 3
  • 5
10

With HTTP v1 API it is different

Documentation

Example:

{
 "message":{
    "topic":"news",
    "notification":{
       "body":"Very good news",
       "title":"Good news"
    },
    "android":{
       "notification":{
          "body":"Very good news",
          "title":"Good news",
          "sound":"default"
       }
    }
  }
}
Andrew
  • 36,676
  • 11
  • 141
  • 113
  • how to write this in php ? – Tabish khan Feb 20 '19 at 10:40
  • @Tabishkhan `$this->message['message']['android']['notification']['sound'] = "default";` – SudoPlz Mar 22 '19 at 15:21
  • What about ios sounds? – Scilef Mar 31 '21 at 13:54
  • 2
    @Scilef Please refer to: https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages. The member corresponding to `android` for iOS is `apns`. Inside `apns` you need a `payload` member, and inside that you need an `aps` member which corresponds to the usual aps payload for iOS as per: https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/generating_a_remote_notification?language=objc – Dave Nottage Apr 23 '21 at 00:57
8

You need to make sure your system enable sound notifications for your app, some devices like Xiaomi disable this option by default, so you will not hear notifications sound until you go to:

Settings > Notifications > (search for your app and click on it name)...

Then enable (Allow Sound) option As shown in this picture:

enter image description here

AnasSafi
  • 5,353
  • 1
  • 35
  • 38
2

do like this

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {

    //codes..,.,,

    Uri sound= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        builder.setSound(sound);

}
DanielBarbarian
  • 5,093
  • 12
  • 35
  • 44
AAA
  • 485
  • 6
  • 23
1

try this....

  public  void buildPushNotification(Context ctx, String content, int icon, CharSequence text, boolean silent) {
    Intent intent = new Intent(ctx, Activity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(ctx, 1410, intent, PendingIntent.FLAG_ONE_SHOT);

    Bitmap bm = BitmapFactory.decodeResource(ctx.getResources(), //large drawable);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(ctx)
            .setSmallIcon(icon)
            .setLargeIcon(bm)
            .setContentTitle(content)
            .setContentText(text)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent);

    if(!silent)
       notificationBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

 NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(1410, notificationBuilder.build());
    }

and in onMessageReceived, call it

 @Override
public void onMessageReceived(RemoteMessage remoteMessage) {


    Log.d("Msg", "Message received [" + remoteMessage.getNotification().getBody() + "]");

    buildPushNotification(/*your param*/);
}

or follow KongJing, Is also correct as he says, but you can use a Firebase Console.

chry
  • 434
  • 7
  • 5
0

I am able to play notification sound even if I send it from firebase console. To do that you just need to add key "sound" with value "default" in advance option.

Saeed Sharman
  • 765
  • 5
  • 24