Android可以像php一样使用苹果推送通知吗?

时间:2011-01-26 07:38:08

标签: php android push-notification

我使用php发布到苹果..

  

$ message = $ error_msg;

  $deviceToken = $dtoken;
  $badge = 1;
  $sound = 'received3.caf';
    $body = array();
    $body['aps'] = array('alert' => $message);
    if ($badge)
            $body['aps']['badge'] = $badge;
    if ($sound)
            $body['aps']['sound'] = $sound;
    $ctx = stream_context_create();
    stream_context_set_option($ctx, 'ssl', 'local_cert', '/home/administrator/applecert/apns-dev.pem');
    $fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
    error_reporting(E_ALL);
    if (!$fp) {
            print "Failed to connect $err $errstr\n";
            return;
            } else {
           print "Connection OK\n";
        }
    $payload = json_encode($body);
    $msg = chr(0) . pack("n",32) . pack('H*', str_replace(' ', '', $deviceToken)) . pack("n",strlen($payload)) . $payload;
    print "sending message :" . $payload . "\n";
    fwrite($fp, $msg);
    fclose($fp);

和andriod有类似的发布方式吗?

谢谢,所有

2 个答案:

答案 0 :(得分:1)

看看谷歌提供的C2DM服务:

http://code.google.com/intl/fr-FR/android/c2dm/

答案 1 :(得分:0)

此代码已经过充分测试。

注意:您需要记住要检查的3个点。

  1. 密码:与IOS开发人员确认。

  2. .PEM:请与您的IOS开发人员确认创建的“.PEM”文件适用于沙盒或实时服务器。

  3. PORT 2195:需要验证服务器上是否已打开此端口。

  4. 如果您已完成这3个步骤,现在您可以使用以下代码发送推送通知,但几乎没有配置更改。

    
     function pushNotification($deviceToken, $msg, $sounds, $type) {
    
            $ctx = stream_context_create();
            stream_context_set_option($ctx, 'ssl', 'local_cert', '');
            // Put your private key's passphrase here: 
            $passphrase = ;
            stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
            $fp = stream_socket_client(
                    'ssl://gateway.sandbox.push.apple.com:2195', $err,
                    $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
            if (!$fp)
                exit("Failed to connect: $err $errstr" . PHP_EOL);
            $body['aps'] = array(
                'alert'  => $msg,
                'sound'  => $sounds,
                'badge'  => 1,
                'type'   => $type,
            );
            $payload = json_encode($body);
            // Build the binary notification
            $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
            // Send it to the server
            $result = fwrite($fp, $msg, strlen($msg));
            // print_r($result);
            fclose($fp);
        }