Pushy is a Java library for sending APNs (iOS and OS X) push notifications



pushy

Pushy is a Java library for sending APNs (iOS and OS X) push notifications. It is written and maintained by the engineers at RelayRides and is built on the Netty framework.

Pushy was created because we found that the other APNs libraries for Java simply didn't meet our needs in terms of performance or (especially) reliability. Pushy distinguishes itself from other libraries with several important features:

  • Asynchronous network IO (via Netty) for maximum performance
  • Efficient connection management
  • Graceful handling and reporting of permanent notification rejections and connection failures
  • Thorough documentation

We believe that Pushy is already the best tool for sending APNs push notifications from Java applications, and we hope you'll help us make it even better via bug reports and pull requests. If you have questions about using Pushy, please join us on the Pushy mailing list or take a look at the wiki. Thanks!

Getting Pushy

If you use Maven, you can add Pushy to your project by adding the following dependency declaration to your POM:

<dependency>
    <groupId>com.relayrides</groupId>
    <artifactId>pushy</artifactId>
    <version>0.4.1</version>
</dependency>

If you don't use Maven, you can download Pushy as a .jar file and add it to your project directly. You'll also need to make sure you have Pushy's runtime dependencies on your classpath. They are:

Pushy itself requires Java 1.6 or newer.

Using Pushy

The main public-facing part of Pushy is the PushManager class, which manages connections to APNs and manages the queue of outbound notifications. Before you can create a PushManager, though, you'll need appropriate SSL certificates and keys from Apple. They can be obtained by following the steps in Apple's "Provisioning and Development" guide.

Once you have your certificates and keys, you can construct a new PushManager like this:

final PushManager<SimpleApnsPushNotification> pushManager =
    new PushManager<SimpleApnsPushNotification>(
        ApnsEnvironment.getSandboxEnvironment(),
        SSLContextUtil.createDefaultSSLContext("path-to-key.p12", "my-password"),
        null, // Optional: custom event loop group
        null, // Optional: custom ExecutorService for calling listeners
        null, // Optional: custom BlockingQueue implementation
        new PushManagerConfiguration(),
        "ExamplePushManager");

pushManager.start();

Many aspects of a PushManager's behavior can be customized. See the PushManagerdocumentation for details. Some important highlights:

  1. If you have multiple PushManager instances, you may want to share an event loop group and/or listener executor service between them to keep the number of active threads at a reasonable level.
  2. By default, a PushManager will use an unbounded public queue; depending on your use case, you may want to use a bounded BlockingQueue implementation or even a SynchronousQueue.
  3. Many other low-level options can be configured by providing a customPushManagerConfiguration.

Once you have your PushManager constructed and started, you're ready to start constructing and sending push notifications. Pushy provides utility classes for working with APNs tokens and payloads. Here's an example:

final byte[] token = TokenUtil.tokenStringToByteArray(
    "<5f6aa01d 8e335894 9b7c25d4 61bb78ad 740f4707 462c7eaf bebcf74f a5ddb387>");

final ApnsPayloadBuilder payloadBuilder = new ApnsPayloadBuilder();

payloadBuilder.setAlertBody("Ring ring, Neo.");
payloadBuilder.setSoundFileName("ring-ring.aiff");

final String payload = payloadBuilder.buildWithDefaultMaximumLength();

pushManager.getQueue().put(new SimpleApnsPushNotification(token, payload));

When your application shuts down, make sure to shut down the PushManager, too:

pushManager.shutdown();

When the PushManager takes a notification from the queue, it will keep trying to send that notification. By the time you shut down the PushManager (as long as you don't give the shutdown process a timeout), the notification is guaranteed to have either been accepted or rejected by the APNs gateway.

Error handling

Pushy deals with most problems for you, but there are two classes of problems you may want to deal with on your own.

Rejected notifications

Push notification providers communicate with APNs by opening a long-lived connection to Apple's push notification gateway and streaming push notification through that connection. Apple's gateway won't respond or acknowledge push notifications unless something goes wrong, in which case it will send an error code and close the connection (don't worry -- Pushy deals with all of this for you). To deal with notifications that are rejected by APNs, Pushy provides a notion of aRejectedNotificationListener. Rejected notification listeners are informed whenever APNs rejects a push notification. Here's an example of registering a simple listener:

private class MyRejectedNotificationListener implements RejectedNotificationListener<SimpleApnsPushNotification> {

    @Override
    public void handleRejectedNotification(
            final PushManager<? extends SimpleApnsPushNotification> pushManager,
            final SimpleApnsPushNotification notification,
            final RejectedNotificationReason reason) {

        System.out.format("%s was rejected with rejection reason %s\n", notification, reason);
    }
}

// ...

pushManager.registerRejectedNotificationListener(new MyRejectedNotificationListener());

Lots of things can go wrong when sending notifications, but rejected notification listeners are only informed when Apple definitively rejects a push notification. All other IO problems are treated as temporary issues, and Pushy will automatically re-transmit notifications affected by IO problems later. You may register a rejected notification listener at any time before shutting down the PushManager.

Failed connections

While running, a PushManager will attempt to re-open any connection that is closed by the gateway (i.e. if a notification was rejected). Occasionally, connection attempts will fail for benign (or at least temporary) reasons. Sometimes, though, connection failures can indicate a more permanent problem (like an expired certificate) that won't be resolved by retrying the connection, and letting thePushManager try to reconnect indefinitely won't help the situation.

You can listen for connection failures with a FailedConnectionListener like this:

private class MyFailedConnectionListener implements FailedConnectionListener<SimpleApnsPushNotification> {

    @Override
    public void handleFailedConnection(
            final PushManager<? extends SimpleApnsPushNotification> pushManager,
            final Throwable cause) {

        if (cause instanceof SSLHandshakeException) {
            // This is probably a permanent failure, and we should shut down
            // the PushManager.
        }
    }
}

// ...

pushManager.registerFailedConnectionListener(new MyFailedConnectionListener());

Generally, it's safe to ignore most failures (though you may want to log them). Failures that result from a SSLHandshakeException, though, likely indicate that your certificate is either invalid or expired, and you'll need to remedy the situation before reconnection attempts are likely to succeed. Poorly-timed connection issues may cause spurious exceptions, though, and it's wise to look for a pattern of failures before taking action.

Like RejectedNotificationListenersFailedConnectionListeners can be registered any time before the PushManager is shut down.

The feedback service

Apple also provides a "feedback service" as part of APNs. The feedback service reports which tokens are no longer valid because the end user uninstalled the receiving app. Apple requires push notification providers to poll for expired tokens on a daily basis. See "The Feedback Service" for additional details from Apple.

To get expired device tokens with Pushy, you'll need to register an ExpiredTokenListener with yourPushManager, then call the requestExpiredTokens method. For example:

private class MyExpiredTokenListener implements ExpiredTokenListener<SimpleApnsPushNotification> {

    @Override
    public void handleExpiredTokens(
            final PushManager<? extends SimpleApnsPushNotification> pushManager,
            final Collection<ExpiredToken> expiredTokens) {

        for (final ExpiredToken expiredToken : expiredTokens) {
            // Stop sending push notifications to each expired token if the expiration
            // time is after the last time the app registered that token.
        }
    }
}

// ...

pushManager.registerExpiredTokenListener(new MyExpiredTokenListener());
pushManager.requestExpiredTokens();

Logging

Pushy uses SLF4J for logging. If you're not already familiar with it, SLF4J is a facade that allows users to choose which logging library to use at deploy time by adding a specific "binding" to the classpath. To avoid making the choice for you, Pushy itself does not depend on any SLF4J bindings; you'll need to add one on your own (either by adding it as a dependency in your own project or by installing it directly). If you have no SLF4J bindings on your classpath, you'll probably see a warning that looks something like this:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

For more information, see the SLF4J user manual.

Pushy uses logging levels as follows:

LevelEvents logged
errorSerious, unrecoverable errors; recoverable errors that likely indicate a bug in Pushy
warnSerious, but recoverable errors; errors that may indicate a bug in caller's code
infoImportant lifecycle events
debugMinor lifecycle events; expected exceptions
traceIndividual IO operations

Limitations and known issues

Although we make every effort to fix bugs and work around issues outside of our control, some problems appear to be unavoidable. The issues we know about at this time are:

  • In cases where we successfully write a push notification to the OS-controlled outbound buffer, but the notification has not yet been written to the network, the push notification will be silently lost if the TCP connection is closed before the OS sends the notification over the network. See#14 for additional discussion.
  • Under Windows, if writing a notification fails after the APNs gateway has rejected a notification and closed the connection remotely, the rejection details may be lost. See #6 for additional discussion.
  • We recommend against using Pushy in a container environment (e.g. a servlet container like Tomcat). Netty, by design, leaves behind some long-running threads and ThreadLocalinstances that we can't reliably clean up, and this can cause leaks when shutting down your app. To be clear, Pushy will send notifications as expected from a container environment, but may not be cleaned up properly at shutdown. If you choose to use Pushy in a container environment, please be aware of the following issues:
    • After shutting down Pushy, a GlobalEventExecutor owned by Netty will continue running for about a second. This can cause warnings in environments that look for thread/resource leaks (e.g. servlet containers), but there is no real harm because the GlobalEventExecutorwill eventually shut itself down. To avoid warnings in these environments, you can add aThread.sleep(1000) call after shutting down Pushy. See #29 for additional discussion.
    • A number of ThreadLocal instances will be left behind by Netty, and these are likely to cause memory leaks. See #73 for details and additional discussion.

License and status

Pushy is available to the public under the MIT License.

The current version of Pushy is 0.4.1. We consider it to be fully functional (and use it in production!), but the public API may change significantly before a 1.0 release.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
React Native是一个开源的移动应用程序框架,可以使用JavaScript和React来开发跨平台的移动应用程序。而Pushy是一个用于在React Native中处理推送通知的第三方库。混编指的是同时使用React Native和Pushy来开发应用程序。 在React Native中使用Pushy可以实现以下功能: 1. 接收推送通知:Pushy提供了一个统一的接口,可以在应用程序中接收来自各种推送通知服务的通知,例如Firebase Cloud Messaging(FCM)和苹果推送通知服务(APNs)。 2. 处理推送通知:开发人员可以使用Pushy提供的API来处理接收到的推送通知,例如显示通知、处理点击事件等。 3. 自定义推送通知:Pushy允许开发人员自定义推送通知的样式和行为,以适应应用程序的需求。 4. 设备注册和解注册:Pushy提供了API用于设备的注册和解注册,以确保设备能够正确地接收推送通知。 混编React Native和Pushy的步骤如下: 1. 在React Native项目中安装Pushy库。 2. 在React Native代码中引入Pushy库,并使用Pushy提供的API来处理推送通知。 3. 在应用程序的入口文件中初始化Pushy,并注册设备以接收推送通知。 4. 在相应的平台的配置文件中配置推送通知服务(例如FCM和APNs)。 5. 使用Pushy提供的API测试和调试推送通知功能。 6. 构建和部署应用程序,确保推送通知功能正常工作。 通过混编React Native和Pushy,开发人员可以在应用程序中实现推送通知功能,从而提升用户体验和增加应用功能。无论是Android还是iOS平台,都可以使用Pushy来方便地处理推送通知。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值