2015-04-04 74 views
1

我想將GCM消息發送到多個註冊設備。當僅發送給一個(作爲測試)時,它可以工作,但是當添加其餘的ID時,我會收到無效的註冊錯誤並且不會發送任何內容。GCM - 一個註冊ID正在工作,但因多個註冊ID失敗

我做到以下幾點:

$sql = "select group_concat(gcm_id) from users where gcm_id is not null"; 

如果只有1 ID(regid1),它的工作原理,如果有一個以上(regid1,regid2),它失敗invalidregistration。我試過如下:

$sql = "select group_concat(concat('\"',gcm_id,'\"')) from users where gcm_id is not null"; 

失敗兩個1號( 「regid1」)和幾個ID( 「gcmid1」, 「gcmid2」)。

regid的格式應該如何工作?

$sql = "select group_concat(gcm_id) from users where gcm_id is not null"; 
    if ($stmt = $con->prepare($sql)) { 
     if ($stmt->execute()) {        
      $stmt->bind_result($gcm_ids); 
      $stmt->fetch();   
      $ids = array($gcm_ids); 
      $stmt->close();       
     } else trigger_error("Problem retrieving gcm ids"); 
    } else trigger_error("Problem retrieving gcm ids"); 
    $con->close();  

if (empty($gcm_ids)) trigger_error("no registrations"); 
    else sendGoogleCloudMessage( $data, $ids); 

    function sendGoogleCloudMessage($data, $gids) { 
     $apiKey = '...'; 
     $url = 'https://android.googleapis.com/gcm/send'; 

     $post = array('registration_ids' => $gids,'data' => $data); 

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

     $ch = curl_init(); 
     // Set URL to GCM endpoint 
     curl_setopt($ch, CURLOPT_URL, $url); 
     // Set request method to POST 
     curl_setopt($ch, CURLOPT_POST, true); 
     // Set our custom headers 
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
     // Get the response back as string instead of printing it 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
     // Set post data as JSON 
     curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post)); 
     // Actually send the push! 
     $result = curl_exec($ch); 
     if (curl_errno($ch)) trigger_error('Error: '.curl_error($ch)); 
     else echo "sent: ".$result; 
     curl_close($ch);     
    } 
+0

後您發送GCM – Pavya 2015-04-04 11:10:39

+0

我更新了所有代碼我的帖子 – Amos 2015-04-04 11:24:47

回答

1

嘗試使用爆炸

$ids = explode(",",$gcm_ids); 

的registration_ids應提交爲陣列。

{ "collapse_key": "score_update", 
    "time_to_live": 108, 
    "delay_while_idle": true, 
    "data": { 
    "score": "4x8", 
    "time": "15:16.2342" 
    }, 
    "registration_ids":["4", "8", "15", "16", "23", "42"] 
} 

更多信息可以在這裏找到https://developer.android.com/google/gcm/http.html

+0

請看看我的代碼更新後,這是我嘗試做,但無濟於事。一個regid確實有效,但有幾個id失敗。 $ sql =「從gcm_id不爲空的用戶中選擇group_concat(gcm_id)」; vs $ sql =「select from gcm_id不爲空的用戶選擇group_concat(concat('\'',gcm_id,'\''));和$ ids = array($ gcm_ids); – Amos 2015-04-04 11:27:18

+0

在將它轉換爲JSON之前,請嘗試使用explode將您的ids字符串轉換爲數組。它可能只是創建一個包含所有ID的索引。其中registration_ids [0] ='「4」,「8」,「15」,「16」,「23」,「42」'代替6個索引。只是嘗試驗證$ gids確實是轉換前的數組 – Phenbach 2015-04-04 11:34:28

+0

謝謝,顯然爆炸是問題,現在有1個或更多的工作! – Amos 2015-04-04 11:39:54