IOS推送-Java

	<properties>
		<pushy.version>0.12.1pushy.version>
	properties>
    <dependency>
        <groupId>com.turogroupId>
        <artifactId>pushyartifactId>
        <version>${pushy.version}version>
    dependency>
	//缓存ApnsClient对象,避免每次都去读取密钥文件
	private static final Map<Boolean,ApnsClient> apnsClientMapCache = new HashMap<>();
    @Value("${is_dev_mode:0}")
    Integer isDevMode;//是不是开发模式,开发模式和正式模式对应不同的密钥文件和key
    
    @Value("${ios_push_file_path}")
    String iosPushFilePath;//IOS推送密钥文件路径
    @Value("${ios_push_key}")
    String iosPushKey;//IOS推送key
    @Value("${ios_push_bundle_id}")
    String iosPushBundleId;//IOS推送bundle-id
    public ApnsClient getAPNSConnect() {
        boolean isDebug=isDevMode.intValue()==1;
        log.info("isDebug?"+isDebug);
        ApnsClient apnsClient = apnsClientMapCache.get(isDebug);
        if (apnsClient == null) {
            try {
                EventLoopGroup eventLoopGroup = new NioEventLoopGroup(4);
                apnsClient = new ApnsClientBuilder().setApnsServer(isDebug?ApnsClientBuilder.DEVELOPMENT_APNS_HOST:ApnsClientBuilder.PRODUCTION_APNS_HOST)
                        .setClientCredentials(new File(iosPushFilePath), iosPushKey)
                        .setConcurrentConnections(4).setEventLoopGroup(eventLoopGroup).build();
                apnsClientMapCache.put(isDebug,apnsClient);
            } catch (Exception e) {
                log.error("ios get pushy apns client failed!");
                e.printStackTrace();
            }
        }
        return apnsClient;
    }
    /**
    * @Param deviceToken IOS设备token
	* @Param alertTitle 推送消息标题
	* @Param alertBody 推送消息内容
	* @Param contentAvailable 传true,在应用关闭时依旧能收到推送,传false,在应用关闭时无法接收推送
	* @Param customProperty 自定义属性
    */
	public String applePush(final String deviceToken, String alertTitle, String alertBody, boolean contentAvailable, JSONObject customProperty) {
        ApnsClient apnsClient = getAPNSConnect();
        ApnsPayloadBuilder payloadBuilder = new ApnsPayloadBuilder();
        if (alertBody != null && alertTitle != null) {
            payloadBuilder.setAlertBody(alertBody);
            payloadBuilder.setAlertTitle(alertTitle);
        }
        //将所有的附加参数全部放进去
        if (customProperty != null) {
            int badge = ValueUtil.getInt(customProperty.get("badge"));
            if (badge > 0) {
                //如果badge小于0,则不推送这个右上角的角标,主要用于消息盒子新增或者已读时,更新此状态
                payloadBuilder.setBadgeNumber(badge);
            }
            for (Map.Entry<String, Object> map : customProperty.entrySet()) {
                payloadBuilder.addCustomProperty(map.getKey(), map.getValue());
            }
        }
        payloadBuilder.setContentAvailable(contentAvailable);

        String payload = payloadBuilder.buildWithDefaultMaximumLength();
        final String token = TokenUtil.sanitizeTokenString(deviceToken);
        String topic = iosPushBundleId;
        SimpleApnsPushNotification pushNotification = new SimpleApnsPushNotification(token, topic, payload);
        final Future<PushNotificationResponse<SimpleApnsPushNotification>> future = apnsClient.sendNotification(pushNotification);
        future.addListener(new GenericFutureListener<Future<PushNotificationResponse>>() {
            @Override
            public void operationComplete(Future<PushNotificationResponse> pushNotificationResponseFuture) throws Exception {
                if (future.isSuccess()) {
                    final PushNotificationResponse<SimpleApnsPushNotification> response = future.getNow();
                    if (response.isAccepted()) {
                    	//成功
                    	logger.info("send notification device  is success ");
                    } else {
                        Date invalidTime = response.getTokenInvalidationTimestamp();
                        log.error("Notification rejected by the APNs gateway: " + response.getRejectionReason());
                        if (invalidTime != null) {
                            log.error("\t…and the token is invalid as of " + response.getTokenInvalidationTimestamp());
                        }
                    }
                } else {
					 logger.error("send notification device  is failed {} ", future.cause().getMessage());
                }
            }
        });
        return "success";
    }

你可能感兴趣的:(JavaEE,ios,java,推送)