使用 push notification API

APNS ( Android Push Notification Service) 是一种在Android 系统上实现推送的一套服务.通过http接口,向APNS服务器发送一个URL请求后,消息即会推送给指定的设备.


使用

1)到官方主页申请免费API, 下载 apns_beta_20110831.jar     

官方主页: www.push-notification.mobi


2) 将apns_beta_20110831.jar添加到工程.

在工程上右键打开“属性”,选择 “Java Build Path”, 在 Libraries 中选择 “Add External JARs”, 选择下载的 apns_beta_20110831.jar.


3) 接收 push notification.

设备在接收到通知的时候会发送一个广播,通过使用BroadcastReceiver 接收并处理收到的通知.

package com.apns.demo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.apns.APNService; 
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, 处理收到的消息
          }
      }
}

4) 启动服务
发送Intent 启动服务,将 chanel 名字以及 此设备的标识 (chanel中唯一表示此设备的字符串) 传递过去:


Intent intent = new Intent(APNService.START);
intent.putExtra("ch", chanel);
intent.putExtra("devId", devId); 
startService(intent);

notes: devId,标示此channel 中设备的唯一id, 可以是唯一用户名, uid, IMEI 等等.


5) 配置AndroidManifest.xml配置 Service/BroadcastReceiver,添加权限


<application android:icon="@drawable/icon"
...
<service android:name="com.apns.APNService" 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" />

推送API:
通过Rect 接口发送通知到设备(登录 www.push-notification.mobi 会有一个测试平台):

http://www.push-notification.mobi/handlers/apns_v1.php?ch=YourChannelId&devId=YourDevId&msg=”hello world”&random=0123&hash=HashCode

参数:
ch: api 
 channel Id.
devId:
 接收设备的Id.
msg:
要发送的消息.
random:一个随机数hash.
ch + g + msg + random + privateKey
MD5 校验码.

返回值:
服务器返回一 xml 格式字符串:

<response result="0" msg="sended"/>

result :
-1: 接失
0: 
送成功
1: 
权发
2: 
限被阻止
3: 
设备不在线
12: chanel 

13: hash code 
不一致
14: 参数不合法
15: 意外错误



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值