[英]OSNotificationPayload cannot be converted to JSONObject
情况:
在我的Quasar混合应用程序中,我需要实现一些本机功能以接收后台通知 。
我从我的API使用OneSignal发送推送通知。
在有效负载中,我添加了一个notification_type
,它将告知通知是否为静默(必须在手机中显示)。
收到通知时,我需要读取该有效负载,但是我无法管理。
编码:
这是NotificationService:
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
的类型, OSNotificationPayload
不是JSONObject
因此您需要像这样读取它:
OSNotificationPayload object = receivedResult.payload;
然后,您从该对象读取值。
尝试此代码示例
JSONObject data = result.notification.payload.additionalData;
String message=result.notification.payload.body!=null?result.notification.payload.body:"";
String title=result.notification.payload.title!=null?result.notification.payload.title:"";
@Khalid Taha的回答是正确的。
但是对于我的特定情况,我可以使用JSONObject。 出问题的是我如何使用它。
如果我以这种方式访问数据,它将起作用:
JSONObject additionalData = receivedResult.payload.additionalData;
然后我可以得到像这样的单个参数:
final String notificationType = additionalData.optString("notification_type");
也许财产additionalData
是通知的内置特性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.