IOS推送 & Android消息推送

本文介绍了如何在iOS中使用APNS进行推送通知,包括前置准备、创建连接、推送逻辑,以及如何在Android中使用FirebaseMessaging发送消息,包括推送结构和可能的错误处理策略。
摘要由CSDN通过智能技术生成

IOS推送 & Android消息推送

IOS

使用APNS 实现IOS消息推送
前置准备:需要APNS证书

//创建APNS链接
    public static ApnsClient getAPNSConnect() {

        if (apnsClient == null) {
            try {
                // 四个线程
                EventLoopGroup eventLoopGroup = new NioEventLoopGroup(4);
                //todo prod
                String resource = new ClassPathResource(ServerConstans.apnsfilepath).getPath();
//                String resource = new File("/xxxxxxxxx/xxxxxxxx/src/main/resources/apns/xxxxx_uat_apns.p12").getPath();
                String resourceLocation = new File(resource).getAbsolutePath();
                File file = ResourceUtils.getFile(resourceLocation);
                apnsClient = new ApnsClientBuilder()
                        //todo prod/uat
//                        .setApnsServer(ApnsClientBuilder.DEVELOPMENT_APNS_HOST)
                        .setApnsServer(ApnsClientBuilder.PRODUCTION_APNS_HOST)    //apns服务器地址
                        .setClientCredentials(file, ServerConstans.apnspass)      //证书密码
                        .setConcurrentConnections(4)							  //线程连接数
                        .setEventLoopGroup(eventLoopGroup).build();				  //线程组
            } catch (Exception e) {
                e.printStackTrace();
                log.error("Get IOS Connect Exception, Please Check:{}", e.getMessage());
            }
        }
        return apnsClient;

    }
/** 
    *	1.deviceToken : IOS等终端设备注册后返回的DeviceToken
    *   2.topic :这是你的主题,大多数情况是bundleId
    * 	3.payload : 发送数据的请求体
    *	4.time : 有效时间
    * 	5.priority : 发送策略 apns-priority 10为立即 5为省电
    * 	6.pushType    推送方式,主要有alert,background,voip,complication,fileprovider,mdm
    */
    public static PushNotificationResponse<SimpleApnsPushNotification> ApplePush(String deviceToken, String topic,
                                                                                 String payload,
                                                                                 Long time, DeliveryPriority priority,
                                                                                 PushType pushType) throws ExecutionException, InterruptedException {
        // 有效时间
        Date invalidationTime = new Date(System.currentTimeMillis() + time);
        Instant instant = invalidationTime.toInstant();
        SimpleApnsPushNotification msg = new SimpleApnsPushNotification(deviceToken, topic, payload, instant, priority, pushType);
        // 开始推送
        PushNotificationFuture<SimpleApnsPushNotification, PushNotificationResponse<SimpleApnsPushNotification>> future = getAPNSConnect().sendNotification(msg);
        PushNotificationResponse<SimpleApnsPushNotification> response = future.get();
        log.info("PushNotificationResponse response:{} ",response);
        return response;
    }

#另外推送可以增加重试机制,防止推送失败

Retryer<PushNotificationResponse<SimpleApnsPushNotification>> retryer = RetryerBuilder.<PushNotificationResponse<SimpleApnsPushNotification>>newBuilder()
                .retryIfException()    //如果出现异常
                .withStopStrategy(StopStrategies.stopAfterAttempt(3))   //重试次数
                .withWaitStrategy(WaitStrategies.fixedWait(10, TimeUnit.SECONDS))  //间隔时长
                .build();
 
 PushNotificationResponse<SimpleApnsPushNotification> response = null;
 try {
            //retry 逻辑
            Callable<PushNotificationResponse<SimpleApnsPushNotification>> task = () ->
                    APNsUtil.ApplePush(deviceToken, "你的topic", "你的请求体,是个json,后面会附上json结构图,可以参考", 60 * 1000L,
                            DeliveryPriority.IMMEDIATE, PushType.ALERT);
            try {
                response = retryer.call(task);
            } catch (RetryException | ExecutionException e) {
                System.out.println(" Retry failed after maximum attempts: " + e.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error(" Ios Send Msg Fail{}", e.getMessage());
            return;
        }

JSON格式
ios推送消息体

Android

 public boolean androidPushMsgxxxxxxxxx(PushMsgVO androidMsg) {
        Notification notice = Notification.builder().setBody(androidMsg.getBody()).setTitle(androidMsg.getTitle()).build();
        builder.setToken(androidMsg.getDeviceToken());// 客户端申请到的token
        builder.setNotification(notice);
        builder.putData("action","xxxxxxx"); //自定义属性
        Message message = builder.build();
        try {
            log.info(" message :"+ JSONObject.toJSONString(message));
            String fcm = FirebaseMessaging.getInstance().send(message);
            log.info(" push android message success.  " + fcm);
        } catch (Exception e) {
            log.error("error message :{}", e.getMessage());
            e.printStackTrace();
            return false;
        }
        return true;
    }

附MessageVo

{
    "header": "",
    "body": "自己可以写哦 Thank you for using my app!",
    "title": "自己写的头",
    "deviceToken": "设备id"
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值