2016-02-05 78 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 –