如何实现android的即时消息投递

来源:互联网 发布:怎么调用存储过程sql 编辑:程序博客网 时间:2024/05/18 00:41

原文取自http://www.push-notification.org/


在服务开启后, APNS Cloud 会与设备保持一个代价非常小的持久TCP连接,当您需要推送消息到您的设备时,向 APNS Cloud 发送一个 http 请求,APNS Cloud 负责将消息投递给设备.


在应用程序中使用 APNS

1. 下载最新的apns的java库 (apns.jar), 并将它添加到您项目的 "Java Build Path"中


2. 编写您自己的广播类(集成自 BroadcastReceiver) 来处理 

"APNService.ON_NOTIFICATION" intent:

public class MyBroadcastReceiver extends BroadcastReceiver {    @Override    public void onReceive(Context context, Intent intent) {        if (intent.getAction().equals(APNService.ON_NOTIFICATION)) {            String str = intent.getStringExtra("data");            //todo, handle the data received        }     }}

3. 在应用程序中启动服务

Intent intent = new Intent(APNService.START);intent.putExtra("ch", channel);intent.putExtra("devId", devId);startService(intent);
channel:渠道id, 每个app key 对应一个渠道, 登陆到开发者页面查看其信息. devId:渠道内设备标识. 用来指定在向渠道内推送消息时的接受者.


4. 修改应用配置文件:

...<application android:icon="@drawable/icon"         ...         <service android:name="com.apns.APNSService" android:label="APNS">            <intent-filter>                <action android:name="com.apns.APNService.START" />                <action android:name="com.apns.APNService.STOP" />                <category android:name="android.intent.category.DEFAULT"/>            </intent-filter>        </service>        <receiver android:name="MyBroadcastReceiver">            <intent-filter>                <action android:name="com.apnsd.APNService.NOTIFICATION" />            </intent-filter>        </receiver>      </application>        <uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />...


推送消息到您的设备

APNS使用REST接口接收请求,之后将消息投递给目标设备, 所以当您需要推送的时候, 需要向我们的网关服务器发送一个http请求
http://www.push-notification.org/handlers/apns_v1.php?ch=YourChannelId&devId=YourDevId&msg=helloooo&random=0123&hash=hashch: 渠道id,devId: 接受设备id,msg: 消息,random: 消息,hash: md5值, 计算方法: md5(ch + devId + msg + random + apiKey).你会得到一个xml格式的响应:     <response result=”0 msg=”sent />错误代码:  -1: 连接错误;   0: 发送成功;   1: 发送失败;   2: 无权操作;   3: 设备不在线;  12: 渠道过期;  13: md5 不匹配;  14: 非法请求;  15: 未知错误;




原创粉丝点击