歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android 實現即時通知

Android 實現即時通知

日期:2017/3/1 11:08:06   编辑:Linux編程

APNS ( Android Push Notification Service) 是一種在Android 系統上實現推送的一套服務.通過http接口,向APNS服務器發送一個URL請求後,消息即會推送給指定的設備.

使用

1)到官方主頁申請免費API, 下載 apns_beta_20110831.jar

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 格式字符串:

  1. <response result="0" msg="sended"/>
result 值:
-1: 服務器連接失敗
0: 發送成功
1: 無權發送
2: 權限被阻止
3: 設備不在線
12: chanel 過期
13: hash code 不一致
14: 參數不合法
15: 意外錯誤
Copyright © Linux教程網 All Rights Reserved