GCM仅向php中最新注册的设备发送消息
我有两台设备在GCM注册。但是,当测试从服务器发送消息时,它只将消息发送到最新注册的设备,而不是所有注册的设备 如何将其更改为发送到这些设备ID:GCM仅向php中最新注册的设备发送消息,php,google-cloud-messaging,Php,Google Cloud Messaging,我有两台设备在GCM注册。但是,当测试从服务器发送消息时,它只将消息发送到最新注册的设备,而不是所有注册的设备 如何将其更改为发送到这些设备ID: <?php //generic php function to send GCM push notification function sendPushNotificationToGCM($registatoin_ids, $message) { //Google cloud messaging GCM-API u
<?php
//generic php function to send GCM push notification
function sendPushNotificationToGCM($registatoin_ids, $message) {
//Google cloud messaging GCM-API url
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
// Google Cloud Messaging GCM API Key
define("GOOGLE_API_KEY", "(API KEY)"); // My API Key form Google console
$headers = array(
'Authorization: key=' . GOOGLE_API_KEY,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
?>
<?php
//this block is to post message to GCM on-click
$pushStatus = "";
if(!empty($_GET["push"])) {
$gcmRegID = file_get_contents("GCMRegId.txt");
$pushMessage = $_POST["message"];
if (isset($gcmRegID) && isset($pushMessage)) {
$gcmRegIds = array($gcmRegID);
$message = array("message" => $pushMessage);
$pushStatus = sendPushNotificationToGCM($gcmRegIds, $message);
}
}
//this block is to receive the GCM regId from external (mobile apps)
if(!empty($_GET["shareRegId"])) {
$gcmRegID = $_POST["regId"];
file_put_contents("GCMRegId.txt",$gcmRegID);
echo "Ok!";
exit;
}
?>
<html>
<head>
<title>Google Cloud Messaging (GCM) Server in PHP</title>
</head>
<body>
<h1>Google Cloud Messaging (GCM) Server in PHP</h1>
<form method="post" action="gcm.php/?push=1">
<div>
<textarea rows="2" name="message" cols="23" placeholder="Message to transmit via GCM"></textarea>
</div>
<div><input type="submit" value="Send Push Notification via GCM" /></div>
</form>
<p><h3><?php echo $pushStatus; ?></h3></p>
</body>
</html>
检查正在存储的新设备ID是否未清除原始内容。即,添加新设备id时的文件操作应为追加模式。这可能会导致仅发送到最新设备的问题。您有什么问题-如何存储多个设备ID或如何向它们发送通知?sendPushNotificationToGCM函数似乎可以正确处理此问题。使用deviceID消息向API发出请求。您需要自己存储设备ID。否则为什么这个问题会有php代码来存储deviceid?存储deviceid不是GOOGLE提供的API。Api将发送通知。所以我的回答是确保新条目不会擦除原始数据是有效的。