2014-02-10 85 views
0

最近我想實現推送消息給所有應用用戶cilent。所以我找到了一個Google服務gcm。由於有多種方法來實施和使用GCM。實際的實現:如何使用GCM將消息推送到應用程序?

Develop by: 
HTTP mode/php + mysql 

Usage: 
send message (notification) to all app users 

下面是從網上教程中的PHP代碼

<?php 
define("GOOGLE_API_KEY", "AIzaSyCJiVkatisdQ44rEM353PFGbia29mBVscA"); 
define("GOOGLE_GCM_URL", "https://android.googleapis.com/gcm/send"); 

function send_gcm_notify($reg_id, $message) { 

    $fields = array(
     'registration_ids' => array($reg_id), 
     'data'    => array("message" => $message), 
    ); 

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

    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, GOOGLE_GCM_URL); 
    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); 
    if ($result === FALSE) { 
     die('Problem occurred: ' . curl_error($ch)); 
    } 

    curl_close($ch); 
    echo $result; 
} 

$reg_id = "APA91bHuSGES.....nn5pWrrSz0dV63pg"; 
$msg = "Google Cloud Messaging working well"; 

send_gcm_notify($reg_id, $msg); 

有沒有適合我的情況,而不是不贊成任何教程?謝謝。我已經獲得了API密鑰,並且Google服務帳戶已準備就緒。

+2

是否有幫助:http://www.androidhive.info/2012/ 10/android-push-notifications-using-google-cloud-messaging-gcm-php-and-mysql/ – user2450263

+0

gcm.jar已貶值,但無論如何感謝您的幫助 – user782104

+1

我的意思是服務器端代碼,但我的錯誤沒有檢查過最新的變化 – user2450263

回答

0

第1步:創建一個PHP頁面,您可以輸入需要的所有用戶

message.php

html> 
<head> 
    <link rel="stylesheet" type="text/css" href="design.css"/> 
</head> 

<body> 
    <div id="container"> 
     <h6>GCM</h6> 
     <h3>MESSAGE</h3> 
     <form action="notification.php" method="post"> 

      <textarea id="message" name="msg" rows="6" cols="41" autofocus="true"></textarea> 
      <br /> 
      <br /> 
      <input type="submit" class="btn_class" value="Send"/> 

     </form> 
    </div> 

</body> 

design.css

要發送的消息
div#container{ 
position:absolute; 
width:400px; 
height:350px; 
top:50%; 
left:50%; 
margin-top:-225px; 
margin-left:-200px; 
box-shadow: 0 0 5px rgba(0, 0, 0, 0.35); 
} 

#message{ 
margin-left:25px; 
} 

.btn_class{ 
color:blue; 
margin-left:170px; 
} 

h6{ 
text-align:center; 
font-family:sans-serif; 
font-size:20px; 
} 

h3{ 
margin-left:30px; 
font-family:sans-serif; 
font-size:14px; 
} 

第2步:創建notification.php文件,收到消息後將它發送給所有你SERS使用您的API密鑰和reg IDS

notification.php

<?php 

    $message=$_POST["msg"]; 
      ........ 
      // construct sql query for database access 

      while($row=mysql_fetch_array($result)){ 

        $registrationIDs[] = $row["gcm_regid"]; // store all reg ids from the column "gcm_regid" in the array 
      } 

      $fields = array(
        'registration_ids' => $registrationIDs, 
        'data' => array("message" => $message), 
      ); 
?> 

的代碼的其餘部分是一樣的你

相關問題