目前我有两个共享相同MySQL数据库的Android应用程序。第一个应用程序将数据发布到数据库。第二个应用程序将显示数据库数据。如何在第一个应用程序将数据发布到数据库后立即向第二个应用程序发送推送通知?
知道如何用GCM解决这个问题吗?
答案 0 :(得分:0)
将数据发布到数据库后,请执行以下代码
$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;
希望这会有所帮助......