java - 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 存储库中的一些示例:
它涉及后台通知,但在这种情况下,它们不会读取receivedResult
.
这是我正在关注的好例子:
在这种情况下,它会像这样读取数据:
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 对象吗?
你知道我为什么会收到这个错误吗?
解决方案
您拥有的有效负载的类型OSNotificationPayload
不是 a JSONObject
,因此您需要像这样阅读它:
OSNotificationPayload object = receivedResult.payload;
然后你从这个对象中读取值。
推荐阅读
- javascript - 防止在 Firefox 浏览器上触发 keyCode 13 建议
- php - 如何在使用exit()时使用fetch_assoc while循环获取所有数据?
- javascript - 如何在 React 中模拟窗口调整大小
- sql-server - SQL Server:如何在嵌套 CASE 上使用带有 LIKE 的 CASE
- spf - SPF 记录的成功率为 0%
- docker - 使用 Docker Toolbox 从图像中提取和更改代码
- r - 从列中的值从最大到最小对R中的数据框进行排序
- java - Android Studio 断言不起作用
- c# - 如何以不同的形式更新图像c#
- css - 在 django-autocomplete-light 3.1.3 上修改 CSS