我已经使用google c2dm成功实现了android推送通知。我总是发送一个设备的post request,一个设备会延迟1-2秒。因此,如果我有1000个设备,我的脚本将需要超过1000秒来完成对所有设备的推送。
我想知道的是,我们是否可以将所有设备的post request发送到google c2dm?如果可以,怎么办?
我正在使用PHP脚本。
下面是我将消息推送到设备的代码:
function sendMessageToPhone($authCode, $deviceRegistrationId, $msgType, $messageText, $infoType, $messageInfo) {
$headers = array('Authorization: GoogleLogin auth=' . $authCode);
$data = array(
'registration_id' => $deviceRegistrationId,
'collapse_key' => $msgType,
'data.message' => $messageText,
'data.type' => $infoType,
'data.data' => $messageInfo
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send");
if ($headers)
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
如果我有更多的设备,我像这样循环:
while($row = mysql_fetch_assoc($result)) {
sendMessageToPhone($authCode, $row['deviceRegistrationId'], GOOGLE_MSG_TYPE, $messageText, $infoType, $messageInfo);
}
谢谢你的帮助
身份验证是所有过程中最广泛(在时间上)的操作,这可能是每次发送之间有1秒延迟的原因。
为了加快这个过程,您不应该每次都进行身份验证。只需验证一次,就可以获得auth令牌。这个令牌有一个特定的TTL,但是Google没有指定任何东西。然后循环遍历您的设备,并使用之前的验证令牌发送。验证令牌可以更改(很少),并且可以在响应头Update-Client-Auth
中找到。
整个过程不应该超过几百毫秒。
也可以考虑使用stream来代替curl
function sendMessageToPhone($authCode, $deviceRegistrationId, $msgType, $messageText, $infoType, $messageInfo) {
$headers = array('Authorization: GoogleLogin auth=' . $authCode);
$data = array(
'registration_id' => $deviceRegistrationId,
'collapse_key' => $msgType,
'data.message' => $messageText,
'data.type' => $infoType,
'data.data' => $messageInfo
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send");
if ($headers)
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}