APNS介绍
顾名思义,APNS为苹果的推送服务,其工作流程如下:
第三方工具包
这里我们使用javapns,除此之外我们还需要bcprov-jdk15-146.jar.
代码实现
首先我们要将消息推送给多台iOS设备,所以应该使用多线程进行消息推送.
我们需要先将服务初始化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public void initPushService() { // 建立与Apple服务器连接 KEY_STORE表示路径 PASSWORD为证书密码 production表示是否使用生产环境 try { AppleNotificationServer server = new AppleNotificationServerBasicImpl(KEY_STORE, PASSWORD, production); NotificationThreads work = new NotificationThreads(server, threadNum); // 对线程的监听 work.setListener(progressListener); // 启动线程 work.start(); } catch (Exception e) { log.error("init Apple Notification Server error!", e); } } |
这里,我们需要所有启动的线程的各种事件进行侦听.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
final NotificationProgressListener progressListener = new NotificationProgressListener() { public void eventThreadStarted(NotificationThread notificationThread) { log.debug("thread start..."); } public void eventThreadFinished(NotificationThread thread) { log.debug("thread #{} finished: pushed messages #{} to {} toward devices", new Object[] { thread.getThreadNumber(), thread.getFirstMessageIdentifier(), thread.getLastMessageIdentifier() }); } public void eventConnectionRestarted(NotificationThread thread) { log.debug("connection restarted in thread #{} because it reached {} notifications per connection", new Object[] { thread.getThreadNumber(), thread.getMaxNotificationsPerConnection() }); } public void eventAllThreadsStarted(NotificationThreads notificationThreads) { log.debug("all threads started:{}", notificationThreads.getThreads().size()); } public void eventAllThreadsFinished(NotificationThreads notificationThreads) { log.debug("all threads finished:{}", notificationThreads.getThreads().size()); } public void eventCriticalException(NotificationThread notificationThread, Exception exception) { log.error("critical exception occurred: ", exception); } }; |
最后,调用方法发布
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
try { PushNotificationPayload payload = new PushNotificationPayload(); String tmp = Nickname + ":" + content; // 判断推送消息是否过长 这里只支持256个字符 if (tmp.length() >= 64) { tmp = tmp.substring(0, 60) + "..."; } payload.addAlert(tmp); // 声音 payload.addSound("sound.wav"); // 图标小红圈的数值 payload.addBadge((int) getUnreadCount(receiver)); // 将要推送的消息和手机唯一标识绑定 work.add(new PayloadPerDevice(payload, token)); } catch (Exception e) { log.error("push message error!", e); } |
如果你看到如下打印,就证明消息已经推送至Apple Push Server.
1 2 3 |
[JavaPNS grouped notification thread in QUEUE mode] DEBUG javapns.notification.PushNotificationManager[line:417] - At this point, the entire 124-bytes message has been streamed out successfully through the SSL connection |
至此,推送通知就发送完毕.
// 图标小红圈的数值
payload.addBadge((int) getUnreadCount(receiver));
这个值是如何动态取得的,谢谢!