2014-03-02 178 views
0

我有點卡在一個問題。我需要將消息通知和警報通知發送到設備。當用戶向其他用戶發送消息時會發送消息通知,並生成警報通知以提醒用戶從服務器發出警報。這意味着我需要多種通知類型。我在我的服務器上使用它來將通知推送到我的設備。Android的GCM發送多個消息到設備

// This is code from the class that take user input 
$notify = "This is message" 
$msg = array("Message" => $notify); 
$sense = $gcm->send_notification($registatoin_ids, $msg); 

//This is the send notification in GCM class 
public function send_notification($registatoin_ids, $message) { 
    // Set POST variables 
    $url = 'https://android.googleapis.com/gcm/send'; 
    $fields = array(
     'registration_ids' => $registatoin_ids, 
     'data' => $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_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); 
    echo $result; 
} 

如何調整上述代碼以符合我的要求。我試圖通過發送

$fields = array(

    "registration_ids" : registatoin_ids, 
    "data" : { 
     "type" : "Message", 
     "Message" : $message, 
    } 

    ); 

但我得到了錯誤的

E/JSON(3444): <b>Parse error</b>: syntax error, unexpected ':', expecting ')' in <b>/home/a8709494/public_html/mobile/GCM.php</b> on line <b>25</b><br /> 

回答

2

您需要使用=>運營商這樣的:

$fields = array(
    "registration_ids" => "registatoin_ids", 
    "data" => array(
    "type" => "Message", 
    "Message" => $message, 
) 
); 
+0

由於它的工作,但我需要把''registration_ids ''在一個單引號中,我收到的消息爲'Received:Bundle [{android.support.content.wakelockid = 1,collapse_key = do_not_collapse,from = xxxxxxxxxxxx,type = Message,Message = {「Message」:「From:Me給你。「}}] '爲什麼它沒有用雙引號。以及我現在如何在客戶端上處理這個字符串。我有GCMIntentService作爲'private void sendNotification(String msg)',我得到'msg =「」Message「:」From:Me to you。「}'' – Nepal12

+1

您可以使用您已經使用過的相同技術:Define幾個嵌套數組來實現這一點。如果你傳遞一個變量,單引號將不會進行替換,只要雙引號將會擴展變量的值。一旦你實現了你的目標,無論是爲了信譽還是反饋,不要忘記接受那些在你之前得到的所有幫助的答案。 – nKn

相關問題