Android/Firebase - 解析 GCM 事件中的时间戳时出错 - 空时间戳

2024-03-26

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

使用网址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)
        ...

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

我试过添加一个timestamp主要有效负载、通知、数据的项目,并且还尝试了诸如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());
    }
}

提前致谢, 克里斯


虽然notification显然是一个受支持的元素(根据 Firebase Web 文档),我摆脱异常的唯一方法是完全删除它,并使用data仅部分,然后在我的应用程序中创建一个通知(而不是让 firebase 执行通知)。

我使用这个网站来研究如何发出通知:https://www.androidhive.info/2012/10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ 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));

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

上面的链接中有更多详细信息,需要进行大量处理,但至少异常消失了,我可以控制通知。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android/Firebase - 解析 GCM 事件中的时间戳时出错 - 空时间戳 的相关文章

  • 虚拟回调接口

    在 Eclipse 为您创建的来自 Google 的示例主从流代码中 片段中包含以下内容 private Callbacks mCallbacks sDummyCallbacks public interface Callbacks pub
  • FCM onMessage 无法在 Firefox 中工作,但可以在 chrome 中工作

    我的代码是工作完美在chrome上 版本103 0 5060 134 但是当我在firefox 103 0 上尝试时它不工作 Service Worker 注册成功 但无法接收通知 消息 控制台中没有显示错误 这是我的代码 顺便说一句 我正
  • Android 中使用黑白 alpha 蒙版的高效位图蒙版

    我想用黑白 alpha 蒙版来掩盖位图 我的蒙版图像是黑白的 黑色区域意味着透明 白色区域意味着不透明 我需要的是 当我使用此蒙版图像来蒙版任何其他图像时 如果蒙版图像的相应区域为黑色 则生成的图像区域应为透明 否则 生成的图像区域应该是不
  • 写入 Android UI Automator 输出控制台

    我正在 Android UI Automator 上编写一个小包装器 通常我们可以在控制台看到测试用例的状态 我可以访问它并添加我自己的消息吗 我努力了System out println 但这没有用 有什么办法可以做到这一点吗 您可以使用
  • relativelayout导致动画不起作用?

    我有一个活动 其布局仅包含一个 VideoView 这是 XML
  • java.lang.IllegalAccessError:预验证类中的类引用在运行测试项目时解析为意外实现?

    在实施项目工作正常之后 我使用第三方库 zxing 实施了项目 然后在我编写了一个测试项目对我的项目进行单元测试之后 运行测试项目后 主项目 类及其方法没有给出任何信息错误 但如果在主项目的该方法中使用任何 zxing 框架类 则会在运行时
  • Firebase Auth - 最近登录多长时间

    我有一个个人资料选项卡 用户可以在其中按编辑并编辑他们的个人资料 我只想在必要时才需要他们的密码 所以想知道用户登录的时间是多少毫秒 这使得它不是最近登录 其中firebase会抛出错误 auth requires recent login
  • 如何在 60 分钟后删除共享首选项

    我想存储登录数据 但希望在 60 分钟后删除该数据 执行此操作的正确方法是什么 在这 60 分钟内可以关闭 停止 打开应用程序 我不想使用内部数据库 这是我的访问代码SharedPreferences sharedpreferences g
  • 如何在Android模拟器中隐藏应用程序图标?

    我有一个应用程序在启动完成后自动启动 但应用程序图标显示在android模拟器中 现在我想向用户隐藏该图标 这样用户就无法知道应用程序已启动 并且他们无法启动该应用程序手动申请 在您的 AndroidManifest xml 文件中 您可能
  • Android Google Map V2:如何在单击另一个标记时更改先前单击的标记的图标

    更新 我通过添加 previousMarker 对象解决了性能问题 因此 只有先前单击的标记将被删除并替换为默认图标 但是 当我单击标记时 信息窗口仍然不显示 我有一个地图视图并在上面设置了一些标记 我想要的是 当我单击一个标记时 它将其图
  • Android 的 Intent 和 Parcelable 对象

    为什么我需要打包我的对象 即使我只需将其发送到同一任务的另一个线程 实际上 我需要打开一个甚至可以在同一线程 主线程 上运行的活动 换句话说 为什么 Google 不提供一个 startActivity 版本 它采用通用对象广告参数而不是捆
  • 以 HTML 格式发送电子邮件

    我想发送 HTML 格式的电子邮件 如下图所示 我怎样才能做到这一点 请帮我 提前致谢 String body new String table tr td br header td tr br br Get b Best Score b
  • 文本视图不显示全文

    我正在使用 TableLayout 和 TableRow 创建一个简单的布局 其中包含两个 TextView 这是代码的一部分
  • Android 中 Activity 之间的 3D 动画

    How to create animation between two Activity look like As Screen shot in android 搜索jazzyviewpager 这是link https github co
  • 通过 Gradle 和 Android Studio 构建和运行应用程序比通过 Eclipse 慢

    我有一个多项目 10 个模块 每次构建大约需要 20 30 秒 当我在 Android Studio 中按 运行 时 每次都必须等待才能重建应用程序 这非常慢 是否可以在 Android Studio 中自动化构建过程 或者您对如何加快此过
  • onPrepareOptionsMenu 复制 ActionBar 中的项目

    当我使用 onPrepareOptionsMenu 添加菜单项时 该菜单项会在操作栏中复制其自身 我正在使用片段并在主要活动的 ActionBar 中创建初始菜单 如下所示 Override public boolean onCreateO
  • 动态更改按钮上的图像视图

    在我的应用程序中 我有按钮和ImageView 当我按下按钮时我想改变ImageView 我的可绘制文件夹中有 5 张图像 按下按钮时 ImageView 根据按钮单击一张一张地更改图像 我想要它的解决方案 感谢任何可以提供帮助的人 维护一
  • 在数组列表中过滤 Filterable 不取消之前的过滤

    我看过过滤器方法文档 其中显示调用过滤器会取消所有先前未执行的过滤请求 并发布一个稍后将执行的新过滤请求 但我收到的实际回调有些不同 在我的实现中 它不会取消先前的过滤器请求并调用publishResults 最近一次搜索条件后的上一次搜索
  • 如何从DataSource.Factory获取数据

    我必须调用此方法才能获取所有人员 我根本无法修改这个方法 Query SELECT FROM PERSON TABLE ORDER BY NAME DESC abstract fun getElements DataSource Facto
  • Android 的代码覆盖率[重复]

    这个问题在这里已经有答案了 可能的重复 Android测试代码覆盖率 Eclipse https stackoverflow com questions 3282702 android test code coverage eclipse

随机推荐

  • Flask - 对 POST 的响应 - 令人困惑的行为

    我对 Flask 中的以下行为感到完全困惑 我确信发生了一些基本的事情 但我不知道这是脚本还是服务器问题 所以我发布了我能想到的最短的示例 该页面有两种方式将数据发布到服务器 一种是通过提交
  • Xcode打印字典的键和值

    Xcode 7 中的打印描述给出了类似于下面的内存地址 尝试了所有选项 但得到这样的输出 3 elements 0 2 elements 0 Output 1 3 elements 0 2 elements 0 type 1 Output2
  • c++ less 运算符重载,使用哪种方式?

    例如 在 C 头文件中 如果我定义了struct Record我想用它进行可能的排序 以便我想重载less operator 以下是我在各种代码中注意到的三种方法 我粗略地注意到 如果我要放Record into a std set map
  • Android maxLines 和 minLines 属性在 XML 中不起作用

    我有一个 XML 文件 其中包含EditText具有这些属性
  • 验证设计模式

    我正在为我们的一个部门编写一个数据验证实用程序 它有以下要求 动态添加新的业务实体 动态地向实体添加新的验证 用于显示业务实体列表及其验证的 UI 用户可以选择开始对所有或选定的业务实体进行验证 如果任何验证失败 UI 将显示验证错误消息
  • 如果应用了 java 插件,Gradle 无法在复合构建中找到 zip 工件

    我有一个 Gradle 项目 它创建一个 zip 工件 我通过定义工件artifacts add default zipTask 我通过以下方式将此项目添加到另一个项目includeBuild并使用 zip 作为依赖项 dependenci
  • 阻止用户将BMP、TIFF等图像上传到Plone中的ImageField

    用户这样做是因为他们可以 但是 图像自动调整大小等功能会出现故障 这让我成为一个悲伤的男孩 如何限制全站图像上传为 GIF PNG 和 JPEG 对于原型 为了灵巧 使用原型 您可以覆盖图像内容类或使用以下架构创建您自己的自定义图像内容类
  • emacs 智能感知

    我知道这个问题已经讨论过很多次了 但是 emacs 中的 c c intellisense 有什么好的方法吗 我一直无法正确设置 cedet 现在我正在开发一个具有庞大代码库的维护项目 如果没有适当的智能感知 管理起来非常困难 目前我正在使
  • 在每个向量条目处求和到向量末尾

    I have X lt c 1 2 3 4 5 6 我想要 X 之和的输出为 Y lt c 21 20 18 15 11 6 我继续读下去rollapply但它一次只能求和 3 个连续的数字 所以有人可以帮助我吗 你需要cumsum Try
  • 将 Console.WriteLine() 输出重定向到字符串

    我需要采取Console WriteLine 输出 并附加到字符串 我无法更改 Main 方法以简单地附加到字符串而不是写入控制台 我需要一种方法来从控制台读取所有写入的行并将它们附加到字符串 目前 我一直在使用FileStream并将控制
  • Android,有没有参考资料可以查看Android默认图标和图像是什么?

    当我想要设计 UI 时 我需要知道什么是预定义图标 我搜索了网络包括http developer android com design index html http developer android com design index h
  • 调整 coord_pol() 直方图中文本标签的位置

    我陷入了一个小标签问题 即用 ggplot2 制作的一系列极坐标直方图 圆环 这些东西怎么称呼 以下是数据和图表外观的简化示例 df lt data frame Attribute1 10 Attribute2 1 Attribute3 2
  • 如何修复 pip install 产生的 gcc 错误?

    我尝试使用以下命令从 PyPI 安装 python 包 sudo pip3 install switcheo 安装失败并显示以下错误消息 gcc Wno unused result Wsign compare Wunreachable co
  • 如何在 JavaScript 中获取查询字符串值?

    这个问题的答案是社区努力 help privileges edit community wiki 编辑现有答案以改进这篇文章 目前不接受新的答案或互动 有没有一种无插件的检索方式请求参数 http en wikipedia org wiki
  • 在 BottomSheetDialog 内的 Viewpager 内嵌套滚动

    简洁版本 我该如何设置NestedScrollingChild of a NestedScrollingParent有多个这样的孩子 长版 我实现了一个BottomSheetDialogFragment其布局由ViewPager 这个vie
  • Delphi 窗口在自定义拖动后失去焦点

    我有这段代码 当我拖动时可以移动我的主窗口MyThingThatDragsIt procedure TMainForm ApplicationMessage var Msg TMsg var Handled Boolean var Scre
  • 查找已选中复选框的顺序

    我正在尝试获取已选中的复选框的顺序 ul class dropdown content checkboxes li li ul
  • 使用cURL上传POST数据和文件

    我想使用 cURL 不仅在 HTTP POST 中发送数据参数 而且还上传具有特定表单名称的文件 我该怎么做呢 HTTP Post 参数 用户 ID 12345 filecomment 这是一个图像文件 HTTP 文件上传 文件位置 hom
  • 在 shell 中生成带有一个特殊字符的随机密码

    我有以下代码 urandom tr dc A Za z0 9 head c 16 这是完美地随机生成密码 我想要两个改变 它只能包含上面列出的一个特殊字符 它应该选择一个随机长度 我尝试过length RANDOM 8 9 然后将长度设置为
  • Android/Firebase - 解析 GCM 事件中的时间戳时出错 - 空时间戳

    我正在构建一个将接收推送通知的 Android 应用程序 我已经完成了 Firebase Cloud Messaging 设置并且几乎可以正常工作 这样我就可以将以下有效负载发送到有效令牌并接收通知和数据 使用网址https fcm goo