【发布时间】: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