首页 > 解决方案 > OSNotificationPayload 无法转换为 JSONObject

问题描述

情况:

在我的Quasar混合应用程序中,我需要实现一些本机功能来接收后台通知

我使用OneSignal从我的 API发送推送通知。

在有效负载中,我添加了一个notification_type通知通知是否静音(必须显示在手机中)。

当我收到通知时,我需要读取该有效负载,但我无法管理。

编码:

这是通知服务:

package com.myapp.app;

import android.util.Log;
import org.json.JSONObject;

import com.onesignal.OSNotificationPayload;
import com.onesignal.NotificationExtenderService;
import com.onesignal.OSNotificationReceivedResult;

public class NotificationService extends NotificationExtenderService {
   @Override
   protected boolean onNotificationProcessing(OSNotificationReceivedResult receivedResult) {

     if (receivedResult != null) {

        JSONObject data = receivedResult.payload;
        // check data - if notification_type is 'silent' than return true otherwise return false
        return false;
     }
   }
}

错误:

error: incompatible types: OSNotificationPayload cannot be converted to JSONObject
        JSONObject data = receivedResult.payload;

在此处输入图像描述

参考:

以下是 OneSignal Android SDK 存储库中的一些示例:

https://github.com/OneSignal/OneSignal-Android-SDK/blob/master/Examples/AndroidStudio/app/src/main/java/com/onesignal/example/NotificationExtenderExample.java

它涉及后台通知,但在这种情况下,它们不会读取receivedResult.

这是我正在关注的好例子:

https://www.programcreek.com/java-api-examples/?code=AppHero2/Raffler-Android/Raffler-Android-master/app/src/main/java/com/raffler/app/service/NotificationService.java #

在这种情况下,它会像这样读取数据: JSONObject additionalData = receivedResult.payload.additionalData;

API:

这就是我从 Laravel API 发送推送通知的方式

private function send_notification_curl($order) {
    $content      = array(
        "en" => "notification message...",
    );
    $fields = array(
        'data' => array(
            'order_id' => $order->id,
            'notification_type' => 'silent'
        ),
        'contents' => $content,
        // some other params...
    );

    $fields = json_encode($fields);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json; charset=utf-8',
        'Authorization: Basic my_key'
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

    $response = curl_exec($ch);
    curl_close($ch);

    return $response;
}

问题:

我怎样才能阅读的内容receivedResult

我可以将其转换为 json 对象吗?

你知道我为什么会收到这个错误吗?

标签: javaandroidcordovaonesignalquasar-framework

解决方案


您拥有的有效负载的类型OSNotificationPayload不是 a JSONObject,因此您需要像这样阅读它:

OSNotificationPayload object = receivedResult.payload;

然后你从这个对象中读取值。


推荐阅读