androidhive 教程使用已弃用的 GCM 处理方法,其 GCMIntentService 是 com.google.android.gcm.GCMBaseIntentService 包的一部分。处理 GCM 的较新方法使用 PlayServices API,其 GCMIntentService 是 com.google.android.gms.gcm.GoogleCloudMessaging 包的一部分。
但是,无论在客户端中使用哪种方法,您最终都会检查额外的意图以提取消息的元素(在 onMessage() 中用于旧方式和 onHandleIntent() 用于较新的方法)。 PHP 服务器端保持不变。
如果您使用
在这个小 php 示例中传递消息
someurl/example.php?message=这是一条消息
<?php session_start();
require 'vals.php';
$randomNum=rand(10,100);
$registrationIDs[] = $regidOne;
$message = $_GET['message'];
$morestuff = 'More text for you';
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registrationIDs,
'data' => array( "message" => $message,
"moredata" => $morestuff),
'delay_while_idle'=> false,
'time_to_live' => 86400,
'collapse_key'=>"".$randomNum.""
);
$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 "Your message has been sent, the results from the Cloud Server were :\n$
echo "<p>";
echo $result;
?>
然后你会在客户端选择消息:
if (intent.hasExtra("message")) {
String theMessage = intent.getStringExtra("message");
//do something
}
并处理您所需的额外数据:
if (intent.hasExtra("moredata")) {
String moreData = intent.getStringExtra("moredata");
//do something else
}
通常,“做某事”可能是启动 Activity。