使用Google C2DM一次向多个设备推送Android通知

5
我已成功使用Google C2DM实现了Android推送通知。我总是为设备发送一个POST请求,而且一个设备需要延迟1-2秒。所以,如果我有1000个设备,我的脚本将需要超过1000秒才能完成对所有设备的推送。
我想知道的事情是,我们能否向Google C2DM发送所有设备的POST请求?如果可以,应该如何操作?
我正在使用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);

}

感谢您的帮助。


你应该添加代码片段,展示你如何发送事件,以便可以提出建议。 - hakre
2个回答

2
认证是整个过程中最耗时的动作,这也可能是每次发送之间存在1秒延迟的原因。
为了加快流程,您不应该每次认证。只需进行一次认证,获取Auth token。此令牌具有一定的TTL,但Google没有指定任何内容。
然后循环遍历设备,并使用先前的Auth token发送。Auth token可能会更改(很少),并且可以在响应头Update-Client-Auth中找到。
整个过程不应超过每个设备的几百毫秒。
还要考虑使用stream而不是curl。

那么,你能带领我完成这个吗? - Kannika
你已经完成了所有的工作。只需确保进行一次身份验证(而不是每次发送消息都要进行身份验证)。也许可以在代码中添加一些基准测试来找出减慢脚本的部分。使用流并非强制性的。 - grunk

0
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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接