gcm消息中的空值

时间:2012-11-29 15:55:15

标签: php android json curl google-cloud-messaging

我正在尝试使用典型的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以检索消息?

1 个答案:

答案 0 :(得分:0)

我认为问题出在这里

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

你必须这样做:

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