您的位置:首页 > 移动开发 > Android开发

使用android push notification service 实现即时通知

2013-06-04 11:07 861 查看
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: 意外错误


example.zip
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: