0

我正在尝试使用典型的 php 后端,使用 curl 将 GCM 推送通知发送到 android 设备。 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 以检索消息?

4

1 回答 1

0

我认为问题出在这里

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

你必须这样做:

$fields = array('registration_ids' => $registrationIDs,
            'data.score' => $data);
于 2012-11-29T18:20:53.170 回答