GCM实施存在疑虑

时间:2013-04-25 00:17:06

标签: php android google-cloud-messaging

我是GCM的新手,也是Android编程的新手。我正在尝试实现推送通知。我的MySQL数据库中有gcm_reg_no。

现在我想将推送通知发送到这些注册ID。你能帮我知道下一步会是什么吗?我是否需要在项目的Android部分添加任何内容?或者我只需要使用PHP将请求发送到GCM服务器?

1 个答案:

答案 0 :(得分:0)

如果您将设备中的GCM注册ID发回服务器并存储在您的数据库中,那么当您想要向他们发送推送通知时,您所要做的就是将数据传递给GCM服务器。 p>

例如,这里是我用来发送推送通知的函数:

//reg array here is an array of the GCM_reg_Ids I wish to send the push to
function push($regarr)
{

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

// Google API KEY, If you don't know your key just walk through the starter guide
$apiKey = "***************";

// Get all the message variables
// These are variables of data you send in the push notification which you use in the 
// Appcode to do stuff
$message = "test" ;
$data = "http://www.google.com";
$preheader = "New Notification";
$header = "test" ;

$fields = array(
              'registration_ids'  => $regarr,
              'data'              => array( "message" => $message,
                                            "preheader" => $preheader,
                                            "header" => $header,
                                            "data" => $data ),
              );

  $headers = array( 
                  'Authorization: key=' . $apiKey,
                  '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_POST, true );
  curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers);
  curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );

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

  // Execute post
  $result = curl_exec($ch);

  // Close connection
  curl_close($ch);


  $json_return = json_decode($result);
  return $json_return;
}

不要忘记确保在PHP上启用了CURL,有很多指南可以提供示例并开始使用GCM,快乐推送消息:D