php - 如何在 MySQL 中插入新行时自动发送 Android 推送通知?

标签 php android mysql push-notification

目前我有 2 个 Android 应用程序共享同一个 MySQL 数据库。第一个应用程序会将数据发布到数据库。第二个应用程序将显示数据库数据。如何在第一个应用程序将数据发布到数据库后立即自动向第二个应用程序发送推送通知?

知道如何用 GCM 解决这个问题吗?

最佳答案

将数据发布到数据库后,执行以下代码

$apiKey = "your api key";

        $db_username    = 'root';
        $db_password    = 'root';
        $db_name        = 'gcm001';
        $db_host        = 'localhost';
        $mysqli = new mysqli($db_host, $db_username, $db_password,$db_name);


        if($mysqli->connect_errno > 0){
            die('Unable to connect to database [' . $mysqli->connect_error . ']');
        }   

        //get registration id's from database, whom you want to send notification  ... assuming you have stored registration ids of 2nd app in database
        $query = "SELECT * FROM RegisteredDevices where userid = $userid";

        $result = mysqli_query($mysqli, $query);
        $i=0;
        $data = array();
        while($row   = mysqli_fetch_assoc($result))
        {
            $data[$i] = $row['reg_id'];
            $i++;
        }

        $registrationIDs = array_values($data);
        //print_r($registrationIDs);

        $url = 'https://android.googleapis.com/gcm/send';



        $fields = array(
                        'registration_ids'  => array_values( $registrationIDs ),
                        'data'              => array( "message" => "Your notification message here" ),
                        );

        $headers = array( 
                            'Authorization: key=' . $apiKey,
                            'Content-Type: application/json'
                        );


        // Open connection
        $ch = curl_init();

        // Set the url, number of POST vars, POST data
        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_VERIFYPEER, false);
        curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $fields ) );

        // Execute post
        $result = curl_exec($ch);

        // Close connection
        curl_close($ch); 

        echo $result;

希望这有帮助......

关于php - 如何在 MySQL 中插入新行时自动发送 Android 推送通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28763214/

相关文章:

php - Zend Framework 管理模块结构

mysql - 可以在 SQL 删除查询中使用别名吗?

php - 如何在 Ubuntu 10.04 中更新 PHP

php - 如何在模板页脚中加载脚本 - CodeIgniter

php - YouTube视频在我的网站上不起作用

Android - 从我的应用程序启动其他应用程序时可以传递参数吗?

android - 多列 ListView 显示零而不是数据库值

android - 如何更改android中默认滚动大小的宽度?

mysql - insert select 忽略某些子查询返回值

php - 删除特殊字符