Android/Firebase - GCM事件中解析时间戳时出现错误 - 时间戳为空。

19

我正在构建一个Android应用程序,该应用程序将接收推送通知。我已经设置了Firebase Cloud Messaging,并基本上可以正常工作,这样我就可以将以下有效令牌的负载发送到通知和数据接收方。

使用url https://fcm.googleapis.com/fcm/send

{
 "to":"<valid-token>",
 "notification":{"body":"BODY TEXT","title":"TITLE TEXT","sound":"default"},
 "data":{"message":"This is some data"}
}

我的应用程序能够正确接收并处理它。

唯一的小问题是,在调试中我会遇到以下异常抛出:

Error while parsing timestamp in GCM event
    java.lang.NumberFormatException: Invalid int: "null"
        at java.lang.Integer.invalidInt(Integer.java:138)
        ...

应用程序不会崩溃,只是看起来不整洁。

我尝试将时间戳项目添加到主载荷、通知、数据中,还尝试了变体(如time),但似乎无法摆脱异常(并且我努力搜索,但找不到答案)。

我该如何传递时间戳以使其不再抛出异常?

编辑:这是我的onMessageReceived方法,但我认为它在此之前就抛出了异常。

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        //TODO Handle the data
    }

    // Check if message contains a notification payload.
    if (remoteMessage.getNotification() != null) {
        Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
    }
}

提前致谢,Chris


你能发布onMessageReceived方法的代码吗? - Naveen Tamrakar
1
没有通知负载,当应用程序不在前台时就不会显示通知。那么通知的替代方案是什么? - schofs
你是在尝试使用Firebase控制台吗? - Naveen Tamrakar
请阅读此链接:https://firebase.google.com/docs/cloud-messaging/android/receive - Naveen Tamrakar
已在下面添加了我的解决方案。简而言之,Firebase 与通知会抛出错误,因此我在本地处理了通知。 - schofs
显示剩余7条评论
8个回答

17
尽管notification显然是Firebase Web文档支持的元素,但唯一让我摆脱异常的方法是完全删除它,并仅使用data部分,然后在我的应用程序中创建通知(而不是让Firebase进行通知)。
我使用了这个网站来解决如何触发通知的问题:https://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ 现在我的通知看起来像下面这样:
    $fields = array("to" => "<valid-token>",
                    "data" => array("data"=>
                                        array(
                                            "message"=>"This is some data",
                                            "title"=>"This is the title",
                                            "is_background"=>false,
                                            "payload"=>array("my-data-item"=>"my-data-value"),
                                            "timestamp"=>date('Y-m-d G:i:s')
                                            )
                                    )
                    );
    ...
    <curl stuff here>
    ...
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

我的onMessageReceived看起来是这样的:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    Log.d(TAG, "From: " + remoteMessage.getFrom());

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

调用handleDataMessage函数,函数如下:

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("message");
        boolean isBackground = data.getBoolean("is_background");
        String timestamp = data.getString("timestamp");
        JSONObject payload = data.getJSONObject("payload");

        // play notification sound
        NotificationUtils notificationUtils = new NotificationUtils(getApplicationContext());
        notificationUtils.playNotificationSound();

        if (!NotificationUtils.isBackgroundRunning(getApplicationContext())) {
            // app is in foreground, broadcast the push message
            Intent pushNotification = new Intent(ntcAppManager.PUSH_NOTIFICATION);
            pushNotification.putExtra("message", message);
            LocalBroadcastManager.getInstance(this).sendBroadcast(pushNotification);

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

            showNotificationMessage(getApplicationContext(), title, message, timestamp, resultIntent);
        }
    } catch (JSONException e) {
        Log.e(TAG, "Json Exception: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
}

这将调用showNotificationMessage

/**
 * Showing notification with text only
 */
private void showNotificationMessage(Context context, String title, String message, String timeStamp, Intent intent) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
}

随后是notificationUtils.showNotificationMessage

public void showNotificationMessage(String title, String message, String timeStamp, Intent intent) {
    showNotificationMessage(title, message, timeStamp, intent, null);
}

public void showNotificationMessage(final String title, final String message, final String timeStamp, Intent intent, String imageUrl) {
    // Check for empty push message
    if (TextUtils.isEmpty(message))
        return;


    // notification icon
    final int icon = R.mipmap.ic_launcher;

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    final PendingIntent resultPendingIntent =
            PendingIntent.getActivity(
                    mContext,
                    0,
                    intent,
                    PendingIntent.FLAG_CANCEL_CURRENT
            );

    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
            mContext);

    final Uri alarmSound = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
            + "://" + mContext.getPackageName() + "/raw/notification");


    showSmallNotification(mBuilder, icon, title, message, timeStamp, resultPendingIntent, alarmSound);
    playNotificationSound();

}

private void showSmallNotification(NotificationCompat.Builder mBuilder, int icon, String title, String message, String timeStamp, PendingIntent resultPendingIntent, Uri alarmSound) {

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

    inboxStyle.addLine(message);

    Notification notification;
    notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
            .setAutoCancel(true)
            .setContentTitle(title)
            .setContentIntent(resultPendingIntent)
            .setSound(alarmSound)
            .setStyle(inboxStyle)
            .setWhen(getTimeMilliSec(timeStamp))
            .setSmallIcon(R.mipmap.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(mContext.getResources(), icon))
            .setContentText(message)
            .build();

    NotificationManager notificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(ntcAppManager.NOTIFICATION_ID, notification);
}

详细信息请查看上面的链接,需要做很多处理,但至少已经解决了异常问题,并且我掌握了通知的控制权。


那种通知格式没有意义,你能不能将它写成JSON格式? - Gerry
@Gerry,谷歌搜索“php json_encode”。他正在使用它将PHP数组编码为JSON。 - ToolmakerSteve

2

我已将com.google.firebase:firebase-messaging更新到17.3.4,问题已经消失。


0
我遇到了同样的错误,通过向有效载荷添加ttl值来解决了这个问题。
{
   "to":"<valid-token>",
   "notification":{"body":"BODY TEXT","title":"TITLE TEXT","sound":"default"},
   "data":{"message":"This is some data"},
   "ttl": 3600
}

0

我曾经遇到过同样的问题,后来我在通知中设置了“body”参数,错误就消失了。


0

替换

 "notification" : {
    "title" : "title !",
    "body" : "body !",
    "sound" : "default"
  },
  "condition" : "'xxx' in topics",
  "priority" : "high",
  "data" : {
....

由(移除通知):

{
  "condition" : "'xxxx' in topics",
  "priority" : "high",
  "data" : {
    "title" : "title ! ",
     "body" : "BODY",
 ......
}

在你的代码中: 替换:

 @Override
        public void onMessageReceived(RemoteMessage remoteMessage) { 
           remoteMessage.getNotification().getTitle();
           remoteMessage.getNotification().getBody();

        }

@Override
    public void onMessageReceived(RemoteMessage remoteMessage) { 
       remoteMessage.getData().get("title");
       remoteMessage.getData().get("body");

    }

0

我的解决方法:

将所有Firebase库升级到最新版本,不仅包括firebase-messaging。在android/app/build.gradle文件中进行修改:

dependencies {
    implementation "com.google.firebase:firebase-core:16.0.0"  // upgraded
    implementation "com.google.firebase:firebase-analytics:16.0.0"  // upgraded
    implementation 'com.google.firebase:firebase-messaging:17.3.4'  // upgraded

    // ...

    implementation "com.google.firebase:firebase-invites:16.0.0"  // upgraded

    // ...
}

并非所有版本都是17.x


0

以下格式(没有通知正文,也没有任何数组)为我解决了时间戳异常问题:

{
  "to": "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
  "data":  {
      "message": "message",
      "title": "hello",
  }
}

已在 http://pushtry.com/ 进行了良好的测试。

我包含这个长长的“eeee…”只是因为它的确刚好是我的令牌大小。


-1
在我的情况下,我的错误是“ AndrodManifest.xml”。
我错过了一个服务(实际上是Android Studio的Firebase助手缺少我的权限。:))。 原文
<service android:name=".fcm.MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>
</application>

解决方案

    <service android:name=".fcm.MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>
    <service android:name=".fcm.MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
</application>

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