javapns是一個java實現的APNs的provider庫,利用這個庫可以向apple的APNs服務器推送基本的以及自定義的APNs消息、從APNs服務器接收詳細發送情況報告(error packet)和查詢反饋信息(feedback)。下面介紹其基本的用法。
一、下載javapns庫和其依賴的庫:
[codesyntax lang="bash"]
svn checkout http://javapns.googlecode.com/svn/trunk/ javapns-read-only
[/codesyntax]
依賴庫:
這幾個都是開源庫。
在工程中導入這幾個庫。
二、推送通知的方法:
Push.alert:推送一條僅包含alert的消息
Push.sound:推送一條僅包含sound的消息
Push.badge:推送一條僅包含badge的消息
Push.combine:推送一條包含alert,sound,badge的消息
也可以自己構造Payload,然后傳遞給Push.payload方法發送一個payload,給一個或多個設備。或者調用Push.payloads方法把payload一對一的發送給設備,這個需要預先構造PayloadPerDevice類的實例。
自己構造構造Payload的實例的基本方法:
[codesyntax lang="java5" lines="fancy"]
PushNotificationPayload payload = new PushNotificationPayload(); //聲明一個空的payload payload.setExpiry(1); //設置payload的過期時間 payload.addAlert("alert message"); //設置alert消息 payload.addBadge(3); //設置badge值 payload.addSound("beep.wav"); //設置聲音 payload.addCustomAlertActionLocKey("launch apns"); //設置ActionLocKey payload.addCustomAlertLocKey("locKey"); //設置LocKey payload.addCustomDictionary("custom1", "value1"); //增加一個自定義鍵值對 List<PushedNotification> notifications = Push.payload(payload, "apns-key+cert-exported-from-mac.p12", "hadoop", false, "def981279b88b3a858b9dc9ea35b893175d5d190e2a271d448ee0679ad5bd880"); //調用Push.payload方法發送這個payload,發回一個已發送的notification的列表
[/codesyntax]
三、處理APNs服務器的反饋
蘋果的推送服務器提供兩個的反饋系統,實際生產過程中,要對兩個反饋系統中的反饋消息都進行檢查,不能只用其一。這兩個反饋系統是:Feedback Service vs Error-response packets 。
javapns系統已經對這兩種反饋系統提供的良好的支持。
(1)Error-response packets
在發送消息之后返回的PushedNotification的response成員中,會保存有蘋果返回的Error-response packets的信息,若消息推送為發生錯誤,則該成員為空null。可通過如下方法使用:
[codesyntax lang="java5" lines="fancy"]
for (PushedNotification notification : notifications) { response = notification.getResponse(); if(response != null) { response.getMessage(); System.out.println(response.getMessage()); } if (notification.isSuccessful()) { System.out.println("Push notification sent successf ully to: " + notification.getDevice().getToken()); } else { String invalidToken = notification.getDevice().getToken(); } }
[/codesyntax]
(2)feedback service
feedback service會列出apple 服務器認為永遠不可達的設備(可能是由于你的client端的應用程序已被刪除等原因)。可通過如下方法使用feedback:
[codesyntax lang="java5" lines="fancy"]
List<Device> devList = Push.feedback("apns-key+cert-exported-from- mac.p12", "hadoop", false); for(Device basicDevice: devList) { System.out.println(basicDevice.getToken()); System.out.println(basicDevice.getDeviceId()); }
[/codesyntax]