Java极光推送工具类

一、使用步骤

目录

1.引入架包

2.创建推送的对象类

3.创建Util类,运行main测试完成


 1.引入架包

代码如下(示例):

        <!-- 极光推送 begin -->
        <dependency>
            <groupId>cn.jpush.api</groupId>
            <artifactId>jpush-client</artifactId>
            <version>3.5.1</version>
        </dependency>
        <dependency>
            <groupId>cn.jpush.api</groupId>
            <artifactId>jiguang-common</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- 极光推送 end -->


2.创建推送的对象类

代码如下(示例):

package com.example.demo2.util.jpush;

import lombok.Data;

import java.util.List;

@Data
public class PushStudent {

    /** 发送目标类型 **/
    private Integer audienceType;

    /** 接收消息的用户别名 **/
    private String aliasName;

    /** 标题 **/
    private String title;

    /** 内容 **/
    private String content;

    /** 跳转类型 0:原生 1:网页 **/
    private Integer goType;

    /** 跳转 pageKey **/
    private String pageKey;

    /** 推送类型id **/
    private Long pushTypeId;

    /** 跳转 url **/
    private String url;

    /** 学生编号 **/
    private String studentCode;

    /** 发送学生消息id **/
    private Long pushStudentId;

    /** 发送目标 **/
    public enum AudienceTypeEnum {
        /** 所有用户 **/
        all(0, "所有用户"),
        /** 标签用户 **/
        tags(1, "标签用户"),
        /** 别名用户 **/
        alias(2, "别名用户"),
        /** 自定义id用户 **/
        registrationId(3, "自定义id用户");


        private int value;
        private String desc;

        public int getValue() {
            return value;
        }

        public String getDesc() {
            return desc;
        }

        AudienceTypeEnum(int value, String desc) {
            this.value = value;
            this.desc = desc;
        }

        public static AudienceTypeEnum getTypeByValue(Integer valueKey) {
            if (null==valueKey) {
                return null;
            }
            for (AudienceTypeEnum enums : AudienceTypeEnum.values()) {
                if (enums.getValue() == valueKey) {
                    return enums;
                }
            }
            return null;
        }
    }
}

 3.创建Util类,运行main测试完成

代码如下(示例):

package com.example.demo2.util.jpush;

import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.CIDResult;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosAlert;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 极光推送客户端
 *
 * @author lhc
 * @since 2021-06-01
 */
@Component
@Slf4j
public class MyJPushClientsUtil {

    //@Value("${jpush.appKey}")
    private String appKey = "";

    //@Value("${jpush.masterSecret}")
    private String masterSecret = "";

    // 此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
    @Value("${jpush.apnsProduction}")
    private String apnsProduction;

    private static JPushClient jPushClient = null;

    public JPushClient getJPushClient() {
        if (jPushClient == null) {
            jPushClient = new JPushClient(masterSecret, appKey);
        }
        return jPushClient;
    }

    /** 极光返回的状态码 **/
    private static Map<Integer, String> codeMap = new HashMap(12){
        private static final long serialVersionUID = 1L;
        {
            put(200,"OK Success!");
            put(400, "错误的请求 该请求是无效的。相应的描述信息会说明原因。");
            put(401, "未验证	没有验证信息或者验证失败");
            put(403, "被拒绝 理解该请求,但不被接受。相应的描述信息会说明原因。");
            put(404, "无法找到 资源不存在,请求的用户的不存在,请求的格式不被支持。");
            put(405, "请求方法不合适 该接口不支持该方法的请求。");
            put(410, "已下线	请求的资源已下线。请参考相关公告。");
            put(429, "过多的请求 请求超出了频率限制。相应的描述信息会解释具体的原因。");
            put(500, "内部服务错误 服务器内部出错了。请联系我们尽快解决问题。");
            put(502, "无效代理 业务服务器下线了或者正在升级。请稍后重试。");
            put(503, "服务暂时失效 服务器无法响应请求。请稍后重试。");
            put(504, "代理超时");
        }
    };

    public static String getCodeStr(int code){
        return (codeMap.get(code)==null || "".equals(codeMap.get(code)))?"无对应状态码值":codeMap.get(code);
    }

    /** 获取 cid,避免同一个通知被调用多次 **/
    private String getCid(JPushClient jPushClient) {
        String value = null;
        try {
            CIDResult cidResult = jPushClient.getCidList(1, "push");
            value = cidResult.cidlist.get(0);
        } catch (APIConnectionException | APIRequestException e) {
            log.error("获取极光cid失败 ", e);
        }
        return value;
    }

    // 扩展消息
    private Map<String, String> getAppExtra(PushStudent pushMessage){
        Map<String, String> extra = new HashMap<>(6);
        extra.put("third_url_encode","false");
        extra.put("pageKey",pushMessage.getPageKey());
        extra.put("url",pushMessage.getUrl());
        extra.put("studentCode",pushMessage.getStudentCode());
        extra.put("goType",""+pushMessage.getGoType());
        extra.put("pushTypeId",""+pushMessage.getPushTypeId());
        return extra;
    }

    private PushResult sendPush(PushPayload pushPayload) {
        log.info("pushPayload={}", pushPayload);
        PushResult pushResult = null;
        try {
            JPushClient jPushClient = this.getJPushClient();
            pushResult = jPushClient.sendPush(pushPayload);
            log.info("" + pushResult);
            if (pushResult.getResponseCode() == 200) {
                log.info("push successful, pushPayload={}", pushPayload);
                System.out.println(pushPayload);
            }
        } catch (APIConnectionException e) {
            log.error("push failed: pushPayload={}, exception={}", pushPayload, e);
            throw new RuntimeException(e.getMessage());
        } catch (APIRequestException e) {
            log.error("push failed: pushPayload={}, exception={}", pushPayload, e);
            throw new RuntimeException(e.getMessage());
        }finally {
            jPushClient.close();
        }
        return pushResult;
    }

    private AndroidNotification getAndroidNotification(PushStudent pushMessage){
        return AndroidNotification.newBuilder()
                //消息体
                .setTitle(pushMessage.getTitle())
                .setAlert(pushMessage.getContent())
                .addExtras(getAppExtra(pushMessage))
                .setBadgeAddNum(1)
                .setBadgeClass("com.skyedu.communal.ui.splash.SplashActivity")
                .setUriAction("com.skyedu.push.StudentOpenClickActivity")
                .setUriActivity("com.skyedu.push.StudentOpenClickActivity")
                .build();
    }

    private IosNotification getIosNotification(PushStudent pushMessage){
        IosAlert alert = IosAlert.newBuilder().setTitleAndBody(pushMessage.getTitle(), "", pushMessage.getContent()).build();
        return IosNotification.newBuilder()
                //消息体
                .setAlert(alert)
                // 通知提示声音或警告通知
                //.setSound(pushMessage.getSound())
                // 应用角标
                .incrBadge(1)
                .addExtras(getAppExtra(pushMessage))
                .setMutableContent(true)
                .build();
    }

    /** 发送极光消息 **/
    public PushResult buildPush(PushStudent mesVo){
        Audience audience;
        PushStudent.AudienceTypeEnum audienceTypeEnum = PushStudent.AudienceTypeEnum.getTypeByValue(mesVo.getAudienceType());
        switch (audienceTypeEnum) {
            case all:
                audience = Audience.all();
                break;
            case tags:
                audience = Audience.tag(mesVo.getAliasName());
                break;
            case alias:
                audience = Audience.alias(mesVo.getAliasName());
                break;
            case registrationId:
                audience = Audience.registrationId(mesVo.getAliasName());
                break;
            default:
                log.error("不支持该类型: audience:{}  ", mesVo.getAudienceType());
                throw new RuntimeException("不支持该类型!");
        }
        PushPayload.Builder builder = PushPayload.newBuilder();
        builder.setPlatform(Platform.android_ios());
        builder.setAudience(audience);

        // 设置发送设备
        Notification.Builder notBuilder = Notification.newBuilder();
        notBuilder.addPlatformNotification(getAndroidNotification(mesVo));
        notBuilder.addPlatformNotification(getIosNotification(mesVo));

        builder.setNotification(notBuilder.build());
        // 其他
        builder.setCid(getCid(this.getJPushClient()));
        builder.setOptions(Options.newBuilder()
                .setApnsProduction(apnsProduction!=null && apnsProduction.equals("true"))
                .setThirdPartyChannelV2(getThirdPartyChannel()).build());
        PushResult pushResult = this.sendPush(builder.build());
        return pushResult;
    }

    public Map getThirdPartyChannel(){
        Map<String, JsonObject> thirdPartyChannel = new HashMap<>();
        JsonObject json = new JsonObject();
        json.addProperty("distribution","secondary_push");
        thirdPartyChannel.put("xiaomi",json);
        thirdPartyChannel.put("huawei",json);
        thirdPartyChannel.put("meizu",json);
        thirdPartyChannel.put("fcm",json);
        thirdPartyChannel.put("oppo",json);
        thirdPartyChannel.put("vivo",json);
        return  thirdPartyChannel;
    }

    public static void main(String[] args) throws APIConnectionException {
        MyJPushClientsUtil jPushUtil = new MyJPushClientsUtil();
        PushStudent mesVo = new PushStudent();
        mesVo.setAudienceType(PushStudent.AudienceTypeEnum.alias.getValue());
        List<String> aliasList = Arrays.asList();

        mesVo.setAliasName("你的别名");
        mesVo.setTitle("消息标题");
        mesVo.setContent("消息内容消息内容消息内容");
        mesVo.setPageKey("pagekey");
        mesVo.setUrl("https://fanyi.baidu.com/?aldtype=16047#auto/zh");
        mesVo.setStudentCode("NO110");
        PushResult pushResult = jPushUtil.buildPush(mesVo);
        System.out.println(pushResult.getOriginalContent());
    }

}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值