Php 如何使用GCM将消息推送到应用程序?
最近我想实现推送消息到所有应用程序用户cilent。所以我找到了一个谷歌服务gcm。因为有很多种方法可以实现和使用GCM。实际执行情况如下:Php 如何使用GCM将消息推送到应用程序?,php,android,mysql,google-cloud-messaging,Php,Android,Mysql,Google Cloud Messaging,最近我想实现推送消息到所有应用程序用户cilent。所以我找到了一个谷歌服务gcm。因为有很多种方法可以实现和使用GCM。实际执行情况如下: Develop by: HTTP mode / php + mysql Usage: send message (notification) to all app users 以下是在线教程中的php代码 <?php define("GOOGLE_API_KEY", "AIzaSyCJiVkatisdQ44rEM353PFGbia29mBVsc
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);
步骤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>
步骤2:创建notification.php文件,该文件在收到消息后将使用api密钥和注册ID将消息发送给所有用户
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 ),
);
?>
其余代码与您的代码相同如果有帮助的话:gcm.jar已贬值,但无论如何感谢您的帮助,因为我的意思是服务器端代码,尽管我犯了错误,我还没有检查最新的代码是否有任何更改。无论如何,我很困惑是否有必要注册cilent设备?我可以简单地将数据发送到我的应用程序中安装的所有设备吗?因为我不需要发送到特定的Cilente,所以安装应用程序的每个移动设备都会成为客户端,所以需要注册yes
<?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 ),
);
?>