目前我有 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/