【问题标题】:Android Push notification sound is played only when app is in foreground but not playing sound when app is in backgroundAndroid推送通知声音仅在应用程序处于前台时播放,但在应用程序处于后台时不播放声音
【发布时间】:2017-05-24 14:14:34
【问题描述】:

我正在使用 FCM 进行推送通知 下面的代码在收到通知时播放声音

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

【问题讨论】:

  • 嗨。您是从自己的应用服务器还是从 Firebase 控制台发送消息?如果来自应用服务器,请包含示例有效负载。
  • 实际上我正在从 fcm 控制台发送通知,是否真的需要发送有效负载才能播放通知音。
  • 只需在您从服务器发送的通知负载中添加 "sound" : "default" 并自动播放声音!

标签: android firebase push-notification android-notifications firebase-notifications


【解决方案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负责播放通知铃声。

 <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 控制台发送通知时,将被视为 通知 消息。当应用处于后台时,通知消息将始终由 Android 设备(系统托盘)自动处理(请参阅Handling messages)。

    这意味着不会调用onMessageReceived()。因此,如果您打算在收到通知时始终播放声音,则必须改用 Data Message*。但是您必须在不使用 Firebase 控制台的情况下发送消息。

    【讨论】:

      【解决方案3】:

      您需要在 Firebase Notification Composer 中的高级设置下启用声音。 :)

      【讨论】:

        【解决方案4】:
        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());
            }
        

        【讨论】:

          【解决方案5】:

          你已经有方法 onMessageReceived, 当应用程序在后台时,firebase 发送 remoteMessage.getData() 类型。 并且 remoteMessage.getNotification() 将为空。所以声音只在应用程序处于前台时播放,而不是在应用程序处于后台时播放。你需要添加

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

          【讨论】:

          • handleDataMessage(json)的实现是什么
          • 这是一种自定义方法,适合您的业务,您可以将其存储在 DB 上,发布事件,做任何您想做的事情。你也可以播放铃声。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-11
          • 1970-01-01
          • 2013-04-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多