当应用程序在前台时,Android推送通知声音会播放,但当应用程序在后台时不会播放声音。

13

我正在使用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 控制台发送消息?如果是从应用服务器发送,请包含一个样例 payload。 - AL.
实际上,我是从 FCM 控制台发送通知的,是否真的需要发送有效载荷才能播放通知音? - Santosh Yadav
1
只需在从服务器发送的通知有效负载中添加“sound”:“default”,它就会自动播放声音! - Loghman Mohamadzadeh
6个回答

13

由于在发送通知对象时不会调用onMessageReceived()方法,因此我创建了一个广播接收器来处理通知的到达:

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>

6
当通过Firebase控制台在Android上发送通知时,它将被视为“通知”消息。当应用程序处于后台时(请参见处理消息),通知消息将始终由Android设备(系统托盘)自动处理。
这意味着不会调用onMessageReceived()。因此,如果您想在收到通知时始终播放声音,则必须改用“数据”消息*。但是,您必须在不使用Firebase控制台的情况下发送消息。

1

您需要在 Firebase 通知合成器的高级设置中启用声音。 :)


0
你需要使用元数据在你的Manifest.xml中设置默认通道,像这样:
<meta-data
     android:name="com.google.firebase.messaging.default_notification_channel_id"
     android:value="NAME_OF_YOUR_DEFAULT_CHANNEL" />

0
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

你已经有了 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) 的实现是什么? - Njeru Cyrus
这是一个定制的方法,适用于您的业务,您可以将其存储在数据库中,发布事件,执行任何您想要的操作。您还可以播放铃声。 - Himesh gosvami

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接