【问题标题】:android push notification to many devices at once time using google c2dmandroid使用google c2dm一次向许多设备推送通知
【发布时间】:2025-12-19 17:00:09
【问题描述】:

我已经使用google c2dm 成功实现了android 推送通知。我总是发送一个设备的发布请求,一个设备延迟 1-2 秒。因此,如果我有 1000 台设备,我的脚本将需要超过 1000 秒才能完成对所有设备的推送。

我想知道的是,我们可以将所有设备的发布请求发送到 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);

}

感谢您的帮助。

【问题讨论】:

  • 您应该添加显示您如何发送事件的代码片段,以便提出建议。

标签: php android push-notification android-c2dm


【解决方案1】:

身份验证是整个过程中最广泛(及时)的操作,这可能是您每次发送之间有 1 秒延迟的原因。

为了加快进程,您不应该每次都进行身份验证。 只需 auth 一次,并获取 Auth 令牌。此令牌具有一定的 TTL,但 Google 未指定任何内容。 然后遍历您的设备,并使用以前的身份验证令牌发送。身份验证令牌可以(很少)更改,可以在响应标头Update-Client-Auth 中找到。

设备的所有过程不应超过几百毫秒。

还可以考虑使用stream 代替 curl

【讨论】:

  • 那么,你能引导我这样做吗?
  • 你已经完成了所有的工作。只需确保验证一次(而不是每次发送消息时)。也许在您的代码中添加一些基准测试以找到减慢脚本的部分。使用流不是强制性的。
【解决方案2】:
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;
}

【讨论】: