Подтвердить что ты не робот

Звук уведомлений Android Push воспроизводится только тогда, когда приложение находится на переднем плане, но не воспроизводит звук, когда приложение находится в фоновом режиме

Я использую FCM для push-уведомления ниже кода для воспроизведения звука при получении уведомления

 public void playNotificationSound() {
        try {

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

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

Я называю этот метод OnMessageReceived, но звук воспроизводится только тогда, когда приложение находится на переднем плане, а не воспроизводится, когда приложение находится в фоновом режиме

 @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();
        }
    }
4b9b3361

Ответ 1

Поскольку onMessageReceived() не вызывается при отправке объекта уведомления, я создал BroadcastReceiver для его обработки при получении уведомления:

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();
    }
}

и добавил его в манифест. Получатель отвечает за воспроизведение мелодии уведомления.

 <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>

Ответ 2

При отправке уведомлений в Android через Firebase Console, это будет рассматриваться как Уведомляющее сообщение. Сообщения уведомления всегда будут обрабатываться автоматически устройством Android (системный лоток), когда приложение находится в фоновом режиме (см. Обработка сообщений).

Это означает, что onMessageReceived() не будет вызываться. Следовательно, если вы намерены всегда воспроизводить звук при получении уведомления, вам придется использовать Data Message * вместо этого. Но вам придется отправлять сообщения без использования Firebase Console.

Ответ 3

Вам нужно включить звук в Firebase Notification Composer в разделе Дополнительные настройки.:)

Ответ 4

private void sendNotification (Строка messageBody, Намерение намерения) {

    //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());
}

Ответ 5

У вас уже есть метод onMessageReceived, firebase отправляет тип remoteMessage.getData(), когда приложение находится в фоновом режиме. и remoteMessage.getNotification() будет null. поэтому звук воспроизводится только тогда, когда приложение находится на переднем плане, а не при воспроизведении приложения в фоновом режиме. вам нужно добавить

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());
        }
    }