使用GCM向多个Android设备发送推送通知

使用GCM向多个Android设备发送推送通知,第1张

使用GCM向多个Android设备发送推送通知

在这里,我使用mysql重写了php,而不是从文件中检索密钥。在这种情况下,我从表中检索所有 regId
,并将它们放入数组中,并将其传递给sendPushNotification函数,以将消息推送给所有人。这里有2个文件,一个用于连接数据库,一个用于GCM:

connect.php:

<?php    $db_host = "localhost";    $db_user = "root"; //change to your database username, it is root by default    $db_pass = '';     //change to your database password, for XAMPP it is nothing for WAMPP it is root    $db_db = 'gcmFirst'; //change to your database name    if(!@mysql_connect($db_host, $db_user, $db_pass) || !@mysql_select_db($db_db)) {        die('couldnt connect to database ' .mysql_error());    }?>

gcm.php

<?phprequire 'connect.php';function sendPushNotification($registration_ids, $message) {    $url = 'https://android.googleapis.com/gcm/send';    $fields = array(        'registration_ids' => $registration_ids,        'data' => $message,    );    define('GOOGLE_API_KEY', 'AIzaSyCjctNK2valabAWL7rWUTcoRA-UAXI_3ro');    $headers = array(        'Authorization:key=' . GOOGLE_API_KEY,        'Content-Type: application/json'    );    echo json_enpre($fields);    $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_SSL_VERIFYPEER, false);    curl_setopt($ch, CURLOPT_POSTFIELDS, json_enpre($fields));    $result = curl_exec($ch);    if($result === false)        die('Curl failed ' . curl_error());    curl_close($ch);    return $result;}$pushStatus = '';if(!empty($_GET['push'])) {    $query = "SELECT regId FROM users";    if($query_run = mysql_query($query)) {        $gcmRegIds = array();        while($query_row = mysql_fetch_assoc($query_run)) { array_push($gcmRegIds, $query_row['regId']);        }    }    $pushMessage = $_POST['message'];    if(isset($gcmRegIds) && isset($pushMessage)) {        $message = array('message' => $pushMessage);        $pushStatus = sendPushNotification($gcmRegIds, $message);    }   }if(!empty($_GET['shareRegId'])) {    $gcmRegId = $_POST['regId'];    $query = "INSERT INTO users VALUES ('', '$gcmRegId')";    if($query_run = mysql_query($query)) {        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 = 'Messages to Transmit via GCM'></textarea>        </div>        <div> <input type = 'submit' value = 'Send Push Notification via GCM'>        </div>        <p><h3><?php echo $pushStatus ?></h3></p>    </form>    </body></html>

您要做的就是创建一个数据库,该数据库具有一个以id,regId和name为列的users表。

希望这是您要寻找的



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5559972.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存