无法从GCM收到消息

时间:2015-10-29 07:18:00

标签: php android

我正在构建基于GCM的应用程序。现在我成功获得了通知,但我得到的消息是一个空对象,我不明白它为什么会发生。

这是GCM的服务器端:

 context.Profiles.Attach(pf);

这是GCM客户端实现: GcmBroadcastReciever:

  <?php


class GCM {



     function __construct() {

        }

        public function send_notification($registatoin_ids, $message) {
            // include config
            include_once 'connection.php';

            // Set POST variables
            $url = 'https://android.googleapis.com/gcm/send';

            $fields = array(
                'registration_ids' => $registatoin_ids,
                'data'             => array("message" => $message),
            );

            $headers = array(
                'Authorization: key=' .GOOGLE_API_KEY,
                'Content-Type: application/json'
            );
            // Open connection
            $ch = curl_init();

            // Set the url, number of POST vars, POST data
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            // Disabling SSL Certificate support temporarly
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));

            // Execute post
            $result = curl_exec($ch);
            if ($result === FALSE) {
                die('Curl failed: ' . curl_error($ch));
            }

            // Close connection
            curl_close($ch);
            return $result;
        }
    }
    ?>

GCMIntentService:

    package com.example.matant.gpsportclient.GoogleCloudNotifications;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;


public class GcmBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        ComponentName comp = new ComponentName(context.getPackageName(),
                GCMIntentService.class.getName());
        context.startService((intent.setComponent(comp)));
        setResultCode(Activity.RESULT_OK);
    }

}

1 个答案:

答案 0 :(得分:1)

GCM以bundle的形式返回数据,尝试使用数组而不是直接使用消息值

 $data=array();
  $data['message']=$message;
  $data['new_data']=$newData; 

然后将该数组传递给GCMfield数组

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

另外请确保在调用send_notification函数时传递!null message:)