gcm 消息中的空值



我正在尝试使用典型的 php 后端使用 curl 向 android 设备发送 GCM 推送通知。php脚本如下:

<?php
//request url
$url    = 'https://android.googleapis.com/gcm/send';
//your api key
$apiKey = 'AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA';
//registration ids
$registrationIDs = array('APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx...');
//payload data
$data   = array('score' => '1-0', 'scorer' => 'Ronaldo', 'time' => '44');
$fields = array('registration_ids' => $registrationIDs,
            'data' => $data);
//http header
$headers = array('Authorization: key=' . $apiKey,
             'Content-Type: application/json');
//curl connection
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
echo $result;
?>  

我在客户端应用程序中使用广播接收器:

private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String newMessage = intent.getExtras().getString("score");
        // Waking up mobile if it is sleeping
        WakeLocker.acquire(getApplicationContext());

        // Showing received message
        lblMessage.append(newMessage + "n");           
        Toast.makeText(getApplicationContext(), " New Message: " + newMessage, Toast.LENGTH_LONG).show();
        // Releasing wake lock
        WakeLocker.release();
    }
};

从 php 脚本的结果来看,我很确定 json 消息正在正确发送。我还在注册的设备中收到通知。但问题是,我收到一条"空"消息。当我只是尝试打印我收到的字符串时,"null"被打印出来。这种说法有问题吗:String newMessage = intent.getExtras().getString("score");?还是我应该解码 json 以检索消息?

我认为问题就在这里

$fields = array('registration_ids' => $registrationIDs,
            'data' => $data);

你必须把它变成这样:

$fields = array('registration_ids' => $registrationIDs,
            'data.score' => $data);

相关内容

最新更新