android - 当应用程序处于前台时无法接收 FCM 通知

标签 android firebase android-fragments firebase-cloud-messaging android-notifications

我正在处理 FCM 通知。当应用程序处于后台时,我的通知工作正常,但当应用程序处于前台时无法接收通知。我几乎尝试了所有方法,但没有用。应用程序在前台时不会收到通知。

list .xml:

       <service
        android:name=".Notification.MyFirebaseMessagingService"
        android:exported="false">
        <intent-filter>

            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <service android:name=".Notification.MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>

代码(FirebaseMessagingService):

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

    try {

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


    Log.e(TAG, "Data Payload: " + remoteMessage.getData().toString());

}

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 the app is in background, firebase itself handles the notification
    }
}

private void handleDataMessage(JSONObject json) {
    Log.e(TAG, "push json: " + json.toString());

    try {
        JSONObject data = json.getJSONObject("data");
        String title = data.getString("title");
        String message = data.getString("body");
        boolean isBackground = data.getBoolean("is_background");
        String imageUrl = data.getString("image");
        String timestamp = data.getString("timestamp");
        JSONObject payload = data.getJSONObject("payload");

        Log.e(TAG, "title: " + title);
        Log.e(TAG, "message: " + message);
        Log.e(TAG, "isBackground: " + isBackground);
        Log.e(TAG, "payload: " + payload.toString());
        Log.e(TAG, "imageUrl: " + imageUrl);
        Log.e(TAG, "timestamp: " + timestamp);


        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.showNotificationMessage("iGrab", message, timestamp, pushNotification);
            notificationUtils.playNotificationSound();


        } else {
            // app is in background, show the notification in notification tray
            Intent resultIntent = new Intent(getApplicationContext(), Splash.class);
            resultIntent.putExtra("message", message);

            // check for image attachment
            if (TextUtils.isEmpty(imageUrl)) {

                showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
            } else {
                // image is present, show notification with image
                showNotificationMessageWithBigImage(getApplicationContext(), title, message, timestamp, resultIntent, imageUrl);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}

最佳答案

FCM 支持两种类型的消息:

  • 通知消息
  • 数据信息

如果服务器发送通知消息,它会自动在系统托盘上显示通知。

Use notification messages when you want FCM to handle displaying a notification on your client app's behalf. Use data messages when you want to process the messages on your client app.

FCM can send a notification message including an optional data payload. In such cases, FCM handles displaying the notification payload, and the client app handles the data payload.

关键在于你的情况:

Notification messages are delivered to the notification tray when the app is in the background. For apps in the foreground, messages are handled by a callback function.

https://firebase.google.com/docs/cloud-messaging/concept-options

关于android - 当应用程序处于前台时无法接收 FCM 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56217297/

相关文章:

java - Android:打开隐藏的 webview Activity 或 fragment

android - 在 Eclipse 中更新现有的 Android 应用程序?

android - PagedList 已弃用

android - 如何在 < 4.0 设备上使用 Actionbarsherlock 在 Actionbar 中强制溢出菜单

javascript - Firebase 身份验证 "auth/invalid-email"和 "The email address is badly formatted."

swift - "Missing required module"当 pod 库仅安装在一个 Target 中时

java - 从代码访问XML枚举值

firebase - 根据用户 oauth 电子邮件设置安全规则 firebase

android - 将数据从 onSharedPreferenceChanged() 发送到另一个 UI Fragment

java - Android Studio(抽屉导航)switch-case "0"原因 "error inflating class fragment"