过去 2 周我们一直在使用 react-native 中的 android 推送通知,我们也尝试使用以下 react native 模块
https://www.npmjs.com/package/react-native-push-notification
使用上述模块,我们能够获取本地通知(来自应用程序的静态通知),该通知有效但未显示来自服务器的通知。我们也试过“https://github.com/oney/react-native-gcm-android”这个..
能够向 GCM 注册并从 GCM 获取 token ,但使用已注册的 token ,无法获取通知和
我们正在使用 php 从服务器发送通知,php 代码如下
这是我们用来从服务器发送通知的代码,
<?php
function sendPushNotificationToGCM($registatoin_ids, $message) {
$url = 'https://android.googleapis.com/gcm/send';
$fields = array('registration_ids' => $registatoin_ids, 'data' => array("title" => 'hi', "message" => $message, ), );
define("GOOGLE_API_KEY", "YOUR API KEY");
$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_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
curl_close($ch);
return $result;
}
?>
我们如何克服这个问题?
最佳答案
尝试下面的 php 代码
<?php
//Generic php function to send GCM push notification
function sendMessageThroughGCM($registatoin_ids, $message) {
//Google cloud messaging GCM-API url
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
// Update your Google Cloud Messaging API Key
define("GOOGLE_API_KEY", "Browswer Key");
$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
//Post message to GCM when submitted
$pushStatus = "GCM Status Message will appear here";
if(!empty($_GET["push"])) {
$gcmRegID = file_get_contents("GCMRegId.txt");
$pushMessage = $_POST["message"];
if (isset($gcmRegID) && isset($pushMessage)) {
$gcmRegIds = array($gcmRegID);
$message = array("m" => $pushMessage);
$pushStatus = sendMessageThroughGCM($gcmRegIds, $message);
}
}
//Get Reg ID sent from Android App and store it in text file
if(!empty($_GET["shareRegId"])) {
$gcmRegID = $_POST["regId"];
file_put_contents("GCMRegId.txt",$gcmRegID);
echo "Done!";
exit;
}
?>
关于android - 为 Android 响应 native 推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35933382/