13
votes

I am using FCM for push notification below code to play sound when notification received

 public void playNotificationSound() {
        try {

            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone r = RingtoneManager.getRingtone(mContext, notification);
            r.play();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

I am calling this OnMessageReceived Method but the sound is only play when app is in foreground,not playing when app is in background

 @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.e(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage == null)
            return;

        // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.e(TAG, "Notification Body: " + remoteMessage.getNotification().getBody());
            handleNotification(remoteMessage.getNotification().getBody());
        }

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

            try {
                JSONObject json = new JSONObject(remoteMessage.getData().toString());
                handleDataMessage(json);
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
        }
    }





 private void handleNotification(String message) {
        if (!NotificationUtils.isAppIsInBackground(getApplicationContext())) {
            // app is in foreground, broadcast the push message
            Intent pushNotification = new Intent(config.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

            // play notification sound
            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        }else if (NotificationUtils.isAppIsInBackground(getApplicationContext())){
            // If the app is in background, firebase itself handles the notification
            NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
            notificationUtils.playNotificationSound();
        }
    }
5
Hi. Are you sending a message from your own App Server or from the Firebase Console? If from an App server, do include a sample payload.AL.
actually i am sending notification from fcm console,is it really necessary to send payload to get notification tone played.Santosh Yadav
Just add "sound" : "default" in your notification payload that you send from the server and its play the sound automatically!Loghman Mohamadzadeh

5 Answers

13
votes

Since onMessageReceived() is not called when a notification object is sent, I've created a BroadcastReceiver to handle it when a notification arrives:

public class NotificationReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    playNotificationSound(context);
}

public void playNotificationSound(Context context) {
    try {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone r = RingtoneManager.getRingtone(context, notification);
        r.play();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

and added it to manifest. The Receiver is responsible to play the notification ringtone.

 <receiver
        android:name=".notification.NotificationReceiver"
        android:exported="true"
        android:permission="com.google.android.c2dm.permission.SEND" >
        <intent-filter>
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
 </receiver>
6
votes

When sending notifications in Android through the Firebase Console, it will be treated as a Notification Message. Notification messages will always be handled automatically by the Android device (System Tray) when the app is in background (see Handling messages).

Which means that onMessageReceived() will not be called. Hence, if you intend to always play a sound upon receiving a notification, you'll have to make use of a Data Message* instead. But you'll have to send the messages without the use of the Firebase Console.

1
votes

You need to enable sound in Firebase Notification Composer under Advanced settings. :)

0
votes
private void sendNotification(String messageBody, Intent intent) {

        //intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent/*.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)*/,
                PendingIntent.FLAG_ONE_SHOT);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setContentIntent(pendingIntent);

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);//<--

        Bitmap bitmap = getBitmapfromUrl(postImageUrl);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.notification_recive)


                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.notification_recive))
                .setContentTitle(postTitle + "")
                .setStyle(new NotificationCompat.BigPictureStyle()
                        .setSummaryText(postTitle + "")
                        .bigPicture(bitmap))
                .setContentText(messageBody)
                .setLights(getResources().getColor(R.color.blue),1000,1500)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)//<--
                .setContentIntent(pendingIntent);


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

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
-1
votes

You Already Have method onMessageReceived, firebase send remoteMessage.getData() type when application is in background. and remoteMessage.getNotification() will be null. so sound is only play when app is in foreground,not playing when app is in background. you need to add

if (remoteMessage.getData().size() > 0) {
        Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

        try {
            JSONObject json = new JSONObject(remoteMessage.getData().toString()); 
            handleNotification(json.getString("msg");//I am assuming message key is msg
            handleDataMessage(json);
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
    }