2016-02-05 79 views
0

我正在实施群组消息的GCM。我的情况:GCM向多个群组发送通知

  • 设备A和B下组1.注册
  • Device C和d下GROUP 2.

参照https://developers.google.com/cloud-messaging/notifications注册,我可以发送通知至组1,但它不可能发送给两个组(第1组和第2组)。

这里是我的代码:以上

<?php 
define('API_ACCESS_KEY', 'MyAPI'); 

$notification_key = 'notificationKeyHere'; 

// prep the bundle 
$msg = array 
(
    'message' => 'here is a message. message', 
    'title'  => 'This is a title. title', 
    'subtitle' => 'This is a subtitle. subtitle', 
    'tickerText' => 'Ticker text here...Ticker text here...Ticker text here', 
    'vibrate' => 1, 
    'sound'  => 1, 
    'largeIcon' => 'large_icon', 
    'smallIcon' => 'small_icon' 
); 
$fields = array 
(
    'to' => $notification_key, 
    'data' => $msg 
); 

$headers = array 
(
    'Authorization: key=' . API_ACCESS_KEY, 
    'Content-Type: application/json' 
); 

$ch = curl_init(); 
curl_setopt($ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send'); 
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; ?> 

代码适用于发送给一个组。 所以后来我想:

$notification_key = array("nKey1", "nKey2"); 

错误产生:

Field "to" must be a JSON string: ["nKey1", "nKey2"] 

所以,我怎么能修改我的代码,这样既可以组收到通知?

+0

目前,就文档而言,目前没有直接发送给许多组的方式。您可以做的是单独向相关设备发送[下游消息](https://developers.google.com/cloud-messaging/http-server-ref#downstream)。看到这[线程](http://stackoverflow.com/questions/13511167/how-to-send-gcm-messages-to-multiple-devices-at-a-时间)。 – gerardnimo

+0

谢谢你。使用“registration_ids”时出现问题。看到这个[线程](http://stackoverflow.com/questions/34835663/gcm-1-email-registered-at-2-devices)@gerardnimo –

回答

0

如果要发送消息到一个单一的设备中使用“到”

'to' => $notification_key, 
'data' => $msg 

但如果你将消息发送到多个设备使用的“registration_ids”,

$ids = array("nKey1", "nKey2"); 

和发送的

'registration_ids' => $ids, 
'data'    => $msg, 
+0

我得到了一个错误是“NotRegistered”,而使用“registration_ids”,但使用时可以:“to”@ yusuf-kartal –

+0

我认为这个答案解决了您的问题。对于第二个(未注册)问题链接有详细的描述http://stackoverflow.com/q/23470252/517134 –