【问题标题】:Push Notification in android c2dmandroid c2dm中的推送通知
【发布时间】:2012-02-20 10:49:16
【问题描述】:

我正在使用 c2dm 在 android 中开发一个示例推送通知应用程序。这是我将消息从服​​务器发送到设备的 PHP 代码。

function sendMessageToPhone($authCode, $deviceRegistrationId, $msgType, $messageText) {

    $headers = array('Authorization: GoogleLogin auth=' . $authCode);
    $data = array(
        'registration_id' => $deviceRegistrationId,
        'collapse_key' => $msgType,
        'data.message' => $messageText //TODO Add more params with just simple data instead           
    );

    $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); 

}
sendMessageToPhone("my application server auth token ","my device id","UTF-8","hello");

但我得到的是“没有信息”。我的模拟器上的通知。我哪里错了?请帮帮我。

【问题讨论】:

  • 执行 cURL 请求的响应是什么?您确定模拟器已注册以接收 C2DM 消息(即与 Google 帐户相关联)吗?您是否在其清单中包含 C2DM 权限?什么版本的安卓?
  • 我是 php 新手。如果我返回 $response,我会得到一些资源 ID。我马上就收到了模拟器上的通知。我已经在清单中包含了所有权限。使用 2.2
  • 当我从 java 应用程序服务器发送消息时,我收到了正确的通知。 (使用java应用服务器认证令牌)
  • 啊,谢谢你的澄清。我从未见过“无信息”问题。然而,我的工作 PHP 代码几乎相同,除了我也有:curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_HEADER, 0); 此外,您可以用它替换 curl_close 行以标记任何错误:if (curl_errno($ch)) { echo curl_error($ch); } else { curl_close($ch); echo $response; }

标签: php android push-notification android-c2dm


【解决方案1】:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://android.apis.google.com/c2dm/send");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Authorization: GoogleLogin auth=$token", "Content-Length: $len", "Content-Type: application/x-www-form-urlencoded"));
echo curl_exec($ch);
curl_close($ch);

这是我的应用程序用来发送 C2DM 消息的 php 代码,其中 $data 是您的数据数组。请注意,Content-Length 是必需的,是您数据的长度。

编辑:您可能还会发现 class 对 php 有用,它可以让发送消息变得更好。

【讨论】:

    猜你喜欢
    • 2011-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-05
    相关资源
    最近更新 更多