【问题标题】:sending push notifications to multiple android devices using GCM使用 GCM 向多个 android 设备发送推送通知
【发布时间】:2014-11-09 16:18:08
【问题描述】:

我在关注http://javapapers.com/android/google-cloud-messaging-gcm-for-android-and-push-notifications/?通过 GCM 发送推送通知。一切正常,但我只能向一台设备发送推送通知。注册另一个设备会替换先前设备的注册 ID。我尝试了 Shardool 在http://javapapers.com/android/android-multicast-notification-using-google-cloud-messaging-gcm/ 中提供的解决方案?但它不工作。

任何建议都会有很大帮助。

这是我的gcm.php 代码,用于注册设备并发送推送通知,但仅限于最近注册的单个设备。

gcm.php

<?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", "MY_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
//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("m" => $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>

请告诉我如何在 GCMRegid.txt 中存储多个设备注册 ID 并向每个注册设备发送通知

【问题讨论】:

    标签: php android notifications google-cloud-messaging


    【解决方案1】:

    在这里,我使用 mysql 重写了 php,而不是从文件中检索密钥。在这种情况下,我从表中检索所有 regIds 并将它们放入一个数组中并将其传递给 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

    <?php
    require '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_encode($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_encode($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 作为列。

    希望这就是你要找的东西

    【讨论】:

    • 我试过了,但它只是搞砸了..你能和我分享一下RegisterActivity.java文件来访问Mysql
    • 我可以在 mysql 数据库中注册设备.. 但是你能和我分享一下整个 gcm.php,它将向多个设备发送推送通知吗??
    • 这里我编辑了我的答案,有 2 个 php 文件,一个用于数据库连接,一个用于 gcm
    • 如何使用“shareRegId”?
    • @s4suryapal 这个解决方案是基于改进 tutorial 关于在数据库中而不是在文件中存储多个 regId,但是关于 shareRegId 它与教程中指出的相同,所以最好从那里理解它。祝你好运
    【解决方案2】:

    我对上面的gcm.php做了一点修改以满足我的需要:

    1. 发送推送通知后,页面应自动重新加载到原始表单。
    2. 它应该显示注册的用户数。
    3. GCM 一次不允许超过 1000 个 regId。所以它应该解决这种情况。 (循环发送 1000 个推送通知的数据包)。

    gcm_main.php:

    <?php
    require 'connect.php'; //this is the same as as other answers on this topic
    
    function sendPushNotification($registration_ids, $message) {
    
        $url = 'https://android.googleapis.com/gcm/send';
        $fields = array(
            'registration_ids' => $registration_ids,
            'data' => $message,
        );
    
        define('GOOGLE_API_KEY', 'your_google_api_key_here');
    
        $headers = array(
            'Authorization:key=' . GOOGLE_API_KEY,
            'Content-Type: application/json'
        );
        echo json_encode($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_encode($fields));
    
        $result = curl_exec($ch);
        if($result === false)
            die('Curl failed ' . curl_error());
    
        curl_close($ch);
        return $result;
    
    }
    
    function redirect($url)
    {
        if (!headers_sent())
        {    
            header('Location: '.$url);
            exit;
            }
        else
            {  
            echo '<script type="text/javascript">';
            echo 'window.location.href="'.$url.'";';
            echo '</script>';
            echo '<noscript>';
            echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
            echo '</noscript>'; exit;
        }
    }
    
    
    $pushStatus = '';
    
    if(!empty($_GET['push'])) {
    
        $query = "SELECT gcm_regid FROM gcm_users";
        if($query_run = mysql_query($query)) {
    
            $gcmRegIds = array();
            while($query_row = mysql_fetch_assoc($query_run)) {
    
                array_push($gcmRegIds, $query_row['gcm_regid']);
    
            }
    
        }
        $pushMessage = $_POST['message'];
        if(isset($gcmRegIds) && isset($pushMessage)) {
    
            $message = array('price' => $pushMessage);
        $regIdChunk=array_chunk($gcmRegIds,1000);
        foreach($regIdChunk as $RegId){
        $pushStatus = sendPushNotification($RegId, $message);}
    
        }   
       $url="url_to_this_php_file";
             redirect($url);
    
    }
    
    
    if(!empty($_GET['shareRegId'])) {
    
        $gcmRegId = $_POST['gcm_regid'];
        $query = "INSERT INTO gcm_users VALUES ('', '$gcmRegId')";
        if($query_run = mysql_query($query)) {
           // echo 'OK';
            exit;
        }   
    }
    ?>
    
    <html>
        <head>
            <title>Whatever Title</title>
        </head>
        <body>
    
            <?php
            include_once 'db_functions.php';
            $db = new DB_Functions();
            $users = $db->getAllUsers();
            if ($users != false)
                $no_of_users = mysql_num_rows($users);
            else
                $no_of_users = 0;
            ?>
        <h1>Whatever you want</h1>
        <h2>Whatever you want</h2>
        <h3>Push Notification Admin Panel</h3>
        <h4>Current Registered users: <?php echo $no_of_users; ?></h4>
        <h4></h4>
        <form method = 'POST' action = 'gcm_main.php/?push=1'>
            <div>
                <textarea rows = "3" name = "message" cols = "75" placeholder = "Type message here"></textarea>
            </div>
            <div>
                <input type = "submit" value = "Send Notification">
            </div>
    
        </form>
        </body>
    </html>
    

    db_connect.php:

        <?php
    
        class DB_Connect {
    
            // constructor
            function __construct() {
    
            }
    
            // destructor
            function __destruct() {
                // $this->close();
            }
    
            // Connecting to database
            public function connect() {
                require_once 'config.php';
                // connecting to mysql
                $con = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
                // selecting database
                mysql_select_db(DB_DATABASE);
    
                // return database handler
                return $con;
            }
    
            // Closing database connection
            public function close() {
                mysql_close();
            }
    
        } 
        ?>
    

    db_functions.php:

            <?php
    
        class DB_Functions {
    
            private $db;
    
            //put your code here
            // constructor
            function __construct() {
                include_once './db_connect.php';
                // connecting to database
                $this->db = new DB_Connect();
                $this->db->connect();
            }
    
            // destructor
            function __destruct() {
    
            }
    
            /**
             * Storing new user
             * returns user details
             */
            public function storeUser($name, $email, $gcm_regid) {
                // insert user into database
                $result = mysql_query("INSERT INTO gcm_users(name, email, gcm_regid, created_at) VALUES('$name', '$email', '$gcm_regid', NOW())");
                // check for successful store
                if ($result) {
                    // get user details
                    $id = mysql_insert_id(); // last inserted id
                    $result = mysql_query("SELECT * FROM gcm_users WHERE id = $id") or die(mysql_error());
                    // return user details
                    if (mysql_num_rows($result) > 0) {
                        return mysql_fetch_array($result);
                    } else {
                        return false;
                    }
                } else {
                    return false;
                }
            }
    
            /**
             * Get user by email and password
             */
            public function getUserByEmail($email) {
                $result = mysql_query("SELECT * FROM gcm_users WHERE email = '$email' LIMIT 1");
                return $result;
            }
    
            /**
             * Getting all users
             */
            public function getAllUsers() {
                $result = mysql_query("select * FROM gcm_users");
                return $result;
            }
    
            /**
             * Check user is existed or not
             */
            public function isUserExisted($id) {
                $result = mysql_query("SELECT gcm_regid from gcm_users WHERE gcm_regid = '$id'");
                $no_of_rows = mysql_num_rows($result);
                if ($no_of_rows > 0) {
                    // user existed
                    return true;
                } else {
                    // user not existed
                    return false;
                }
            }
    
        public function deleteUser($id){
        $result=mysql_query("DELETE FROM gcm_users WHERE gcm_regid = '$id'");
    
        }    
    
    
        }
    
    ?>
    

    config.php:

    <?php
    /**
     * Database config variables
     */
    define("DB_HOST", "localhost");
    define("DB_USER", "root");
    define("DB_PASSWORD", "");
    define("DB_DATABASE", "gcm");
    
    /*
     * Google API Key
     */
    define("GOOGLE_API_KEY", "your_google_api_key_here"); // Place your Google API Key
    ?>
    

    编辑:

    我已经重新编写了 PHP 代码,并进行了一些改进并使用了 MySqli(而不是 MySql)。它在Github

    【讨论】:

    • 我已经使用sendPushNotification()并手动输入所有值,curl返回消息"results":[{"error":"NotRegistered"}]我能做什么
    • @Irfan 发送到 GCM 的设备 ID 未注册。您需要先使用 GCM 正确注册您的 android,然后将 id 存储在服务器中。如果您确实使用 GCM 注册了 id,那么它可能会过期(虽然很奇怪),所以您可能需要重新注册。如果您使用的是模拟器,也可能会发生这种情况。用真机测试一下……
    【解决方案3】:

    向多个设备发送推送通知与我们向单个设备发送相同。 只需将所有注册设备的注册令牌存储到您的服务器即可。 并且在使用 curl 调用推送通知时(我假设您使用 php 作为服务器端)将所有注册 id 放入一个数组中。 这是一个示例代码

    <?php
    //Define your GCM server key here 
    define('API_ACCESS_KEY', 'your server api key');
    
    //Function to send push notification to all 
    function sendToAll($message)
    {
        $db = new DbOperation();
        $tokens = $db->getAllToken();
        $regTokens = array();
        while($row = $tokens->fetch_assoc()){
            array_push($regTokens,$row['token']);
        }
        sendNotification($regTokens,$message);
    }
    
    
    //function to send push notification to an individual 
    function sendToOne($email,$message){
        $db = new DbOperation();
        $token = $db->getIndividualToken($email);
        sendNotification(array($token),$message);
    }
    
    
    //This function will actually send the notification
    function sendNotification($registrationIds, $message)
    {
        $msg = array
        (
            'message' => $message,
            'title' => 'Android Push Notification using Google Cloud Messaging',
            'subtitle' => 'www.simplifiedcoding.net',
            'tickerText' => 'Ticker text here...Ticker text here...Ticker text here',
            'vibrate' => 1,
            'sound' => 1,
            'largeIcon' => 'large_icon',
            'smallIcon' => 'small_icon'
        );
    
        $fields = array
        (
            'registration_ids' => $registrationIds,
            'data' => $msg
        );
    
        $headers = array
        (
            'Authorization: key=' . API_ACCESS_KEY,
            'Content-Type: application/json'
        );
    
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://android.googleapis.com/gcm/send');
        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);
        curl_close($ch);
    
        $res = json_decode($result);
    
        $flag = $res->success;
        if($flag >= 1){
            header('Location: index.php?success');
        }else{
            header('Location: index.php?failure');
        }
    }
    

    来源:Google Cloud Messaging Tutorial

    【讨论】:

      【解决方案4】:

      以下代码可让我向所有注册用户发送通知:

      <?php
      header("Access-Control-Allow-Origin: *"); 
      
      $db_host = 'localhost'; //hostname
      $db_user = ''; // username
      $db_password = ''; // password
      $db_name = ''; //database name
      $link = mysqli_connect($db_host,$db_user,$db_password, $db_name);
      
      
      
      
      $query = "select * from device_notification_id";
      $result = mysqli_query ($link,$query);
      while($row=mysqli_fetch_array($result)){
       		
       		$device_to[] =  $row[device_id];
       		
       			
      }
      
      
      
      if(isset($_POST['submit'])){
      
      $title=$_POST['title'];
      $message=$_POST['message'];
      for($i=0 ; $i< sizeof($device_to) ; $i++)
      {
      //echo $to[$i];
      
      $to = $device_to[$i];
      
      sendPush($to,$title,$message);
      }
      
      
      }
      	function sendPush($to,$title,$message)
      	{
      // API access key from Google API's Console
      // replace API
      		define( 'API_ACCESS_KEY', 'AIdfSyCd8ha2wop84LKtpQvRmCEiY8ZLpeTg2-o');
      		$registrationIds = array($to);
      		
      		
      
      	$msg = array
      	(
      	'message' => $message,
      	'title' => $title,
      	'vibrate' => 1,
      	'sound' => 1
      
      // you can also add images, additionalData
      );
      
      
      	$fields = array
      	(
      		'registration_ids' => $registrationIds,
      		'data' => $msg
      );
      $headers = array
      (
      'Authorization: key=' . API_ACCESS_KEY,
      'Content-Type: application/json'
      );
      
      $ch = curl_init();
      curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
      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 );
      curl_close( $ch );
      
      echo $result;
      }
      
      
      ?>
      <html>
      <form  method="POST">
      <input type="text" name="title">
      <input type="text" name="message">
      <input type="submit" name="submit" value="submit">
      </form>
      </html>

      【讨论】:

      • 你能解释一下什么是注册 ID 以及在哪里/如何获得它吗?
      猜你喜欢
      • 2017-01-08
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多