jPush极光推送 测试demo以及绑定regid/标签/别名

jPush极光推送 测试demo以及绑定regid/标签/别名

推送Jpushdemo

您好 这是我头一次使用博客来记录平时一些工作代码,同时也希望可以帮助别人。接触开发工作时间不长 大牛勿喷 不扯闲篇儿了 开撸。

依赖

首先导入Jpush依赖我这里使用的是jpush-3.4.2
	<dependency>
            <groupId>cn.jpush.api</groupId>
            <artifactId>jpush-client</artifactId>
            <version>3.4.2</version>
    </dependency>
    <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>
        <dependency>
            <groupId>cn.jpush.api</groupId>
            <artifactId>jpush-client</artifactId>
            <version>3.4.2</version>
        </dependency>
        <dependency>
            <groupId>cn.jpush.api</groupId>
            <artifactId>jiguang-common</artifactId>
            <version>1.1.7</version>
        </dependency>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.6.Final</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.7</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

代码

首先需要登入极光推送官网注册账号获取AppKey,Master Secret
连接https://www.jiguang.cnjPush极光推送 测试demo以及绑定regid/标签/别名
Config类来存放AppKey,Master Secret

public class JPushConfig {
    public static String APP_KEY = "AppKey";
    public static String MASTER_SECRET = "Master Secret";
}

**Utils工具类 重点来了 这个工具类就是来写你要给那部手机推送消息。里面涉及了 android/ios手机系统 标签别名 regid这里重点说下regid这个id是你手机的id 有这个id才能跟你的手机进行绑定 ,上官网下载一个android/ios端的JPush SDK demo **

public class JPushUtil {




    //Android
    public static void jpushAndroid(Map<String, String> parm) {
        //创建JPushClient
        JPushClient jpushClient = new JPushClient(JPushConfig.MASTER_SECRET, JPushConfig.APP_KEY);
        //推送的关键,构造一个payload
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.android())//指定android平台的用户
                .setAudience(Audience.all())//项目中的所有用户
                .setAudience(Audience.alias(parm.get("alias")))//设置别名
                .setAudience(Audience.tag(parm.get("tags").split("tag1")))//设置标签发送,群发
                .setAudience(Audience.registrationId(parm.get("id")))//registrationId指定用户
                .setNotification(Notification.android(parm.get("msg"), "这是title", parm))
                //发送内容
                .setOptions(Options.newBuilder().setApnsProduction(true).setTimeToLive(7200).build())
                //指定开发环境
                .setMessage(Message.content(parm.get("msg")))//自定义信息
                .build();
        try {
            PushResult pu = jpushClient.sendPush(payload);
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
    }

    //ios
    public static  void jpushIOS(Map<String, String> parm) {
        //创建JPushClient
        JPushClient jpushClient = new JPushClient(JPushConfig.MASTER_SECRET, JPushConfig.APP_KEY);
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.ios())//ios平台的用户
                .setAudience(Audience.all())//所有用户
                .setAudience(Audience.registrationId(parm.get("id")))//registrationId指定用户
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(parm.get("msg"))
                                .setBadge(+1)
                                .setSound("happy")//提示音
                                .addExtras(parm)
                                .build())
                        .build())
                .setOptions(Options.newBuilder().setApnsProduction(false).build())
                .setMessage(Message.newBuilder().setMsgContent(parm.get("msg")).addExtras(parm).build())//自定义信息
                .build();
        try {
            PushResult pu = jpushClient.sendPush(payload);
            System.out.println(pu.toString());
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
    }

    //All
    public static void jpushAll(Map<String, String> parm) {
        //创建JPushClient
        JPushClient jpushClient = new JPushClient(JPushConfig.MASTER_SECRET, JPushConfig.APP_KEY);
        //创建option
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.all())  //所有平台的用户
                .setAudience(Audience.registrationId(parm.get("id")))//registrationId指定用户
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder() //发送ios
                                .setAlert(parm.get("msg")) //消息体
                                .setBadge(+1)
                                .setSound("happy") //ios提示音
                                .addExtras(parm) //附加参数
                                .build())
                        .addPlatformNotification(AndroidNotification.newBuilder() //发送android
                                .addExtras(parm) //附加参数
                                .setAlert(parm.get("msg")) //消息体
                                .build())
                        .build())
                .setOptions(Options.newBuilder().setApnsProduction(true).build())//指定开发环境 true为生产模式 false 为测试模式 (android不区分模式,ios区分模式)
                .setMessage(Message.newBuilder().setMsgContent(parm.get("msg")).addExtras(parm).build())//自定义信息
                .build();
        try {
            PushResult pu = jpushClient.sendPush(payload);
            System.out.println(pu.toString());
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }
    }
}

到这里推送的核心部分已经完成 ,下面是我老大逼我读源码后我整理的 一些功能模块。
绑定手机号/手机号解绑/判断手机号是否绑定 | 生成标签/删除更新标签 | 生成别名/删除别名

public class clientServiceImpl {


    private static Logger LOG = LoggerFactory.getLogger(clientServiceImpl.class);

    private String regid = "" ;
    protected static JPushClient jPushClient = null ;
    public clientServiceImpl(String t){
          regid=t;
    }

    /**
     * 声明jPushClient
     * @return
     */
    public JPushClient getJPushClient(){

        return new JPushClient(JPushConfig.MASTER_SECRET,JPushConfig.APP_KEY);
    }

    /**
     *
     * @param mobile
     * @return
     * regid和手机号进行关联
     */
    public boolean bindMobile(String mobile) {

        try {
            DefaultResult result = getJPushClient().bindMobile(regid, mobile);
            LOG.info("Got result " + result);
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Error Message: " + e.getErrorMessage());
        }finally {
            getJPushClient().close();
        }
        return false;
    }

    /**
     *
     * @param name
     * @return
     *生成别名
     */

    public boolean bindAlias(String name, HashSet<String> tagsToAdd) {
        try {
            DefaultResult defaultResult = getJPushClient().updateDeviceTagAlias(regid, name, tagsToAdd,
                    new HashSet<String>(getJPushClient().getDeviceTagAlias(regid).tags));
            LOG.info("Got result"+defaultResult);
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
            e.printStackTrace();
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            e.printStackTrace();
        }finally {
            getJPushClient().close();
        }
        return false;
    }

    /**
     * 生成标签
     * @param name
     * @param tagsToAdd
     * @return
     */

    public boolean bindTags(String name, HashSet<String> tagsToAdd){
        try {
            DefaultResult result = getJPushClient().updateDeviceTagAlias(regid, name
                    , new HashSet<String>(Collections.singleton((getJPushClient().getDeviceTagAlias(regid).alias)))
                    , tagsToAdd);
            LOG.info("Got result"+result);
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
            e.printStackTrace();
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            e.printStackTrace();
        }finally {
            getJPushClient().close();
        }
        return false;
    }

    /**
     * 更新标签
     * @param
     * @return
     */
    public boolean changeTags(List<?> list) {
        for (int i = 0;i<list.size();i++){
            try {
                DefaultResult defaultResult = getJPushClient().addRemoveDevicesFromTag(
                        String.valueOf(list.get(i))
                        , Collections.singleton(regid)
                        , null);
                LOG.info("Got result" + defaultResult);
            } catch (APIConnectionException e) {
                LOG.error("Connection error. Should retry later. ", e);
                e.printStackTrace();
            } catch (APIRequestException e) {
                LOG.error("Error response from JPush server. Should review and fix it. ", e);
                e.printStackTrace();
            }
        }

        return false;
    }

    /**
     * 删除标签
     */

    public void clearTags() {
        try {
            DefaultResult defaultResult = getJPushClient().deleteTag(String.valueOf(getJPushClient().getDeviceTagAlias(regid).tags),regid);
            LOG.info("Got result"+defaultResult);
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
        }finally {
            getJPushClient().close();
        }
    }


    /**
     * 判断设备与别名的绑定关系
     * @return
     */
    public BooleanResult hasMobile() {
        BooleanResult deviceInTag = null;
        try {
             deviceInTag = getJPushClient().isDeviceInTag(
                    String.valueOf(getJPushClient().getDeviceTagAlias(regid).alias), regid);
            LOG.info("Got result" + deviceInTag);
            return deviceInTag ;
        } catch (APIConnectionException e) {
            e.printStackTrace();
        } catch (APIRequestException e) {
            e.printStackTrace();
        }finally {
            getJPushClient().close();
        }
        return deviceInTag ;
    }

    /**
     * 删除别名
     * @param
     */

    public void unbindAlias() {
        try {
            DefaultResult defaultResult = getJPushClient().updateDeviceTagAlias(regid, true, true);
            LOG.info("Got result"+defaultResult);
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
            e.printStackTrace();
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            e.printStackTrace();
        }finally {
            getJPushClient().close();
        }
    }

    /**
     * 解除绑定
     */

    public void unbindMobile() {
        DefaultResult result = null;
        try {
            result = getJPushClient().bindMobile(regid, null);
            LOG.info("Got result"+result);
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
            e.printStackTrace();
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            e.printStackTrace();
        }
    }


     public HashMap<String,Object> dgetInfo() {
         HashMap<String,Object> map = new HashMap<>();
         try {
              map.put("alias",getJPushClient().getDeviceTagAlias(regid).alias);
              map.put("tags",getJPushClient().getDeviceTagAlias(regid).tags);
              map.put("mobile",getJPushClient().isDeviceInTag(
                     String.valueOf(getJPushClient().getDeviceTagAlias(regid).alias), regid));
             LOG.info("alias"+" : "+map.get("alias")+" , "+"teges"+" : "+map.get("tags")+" , "+"mobile"+" : "+map.get("mobile"));
         } catch (APIConnectionException e) {
             LOG.error("Connection error. Should retry later. ", e);
             e.printStackTrace();
         } catch (APIRequestException e) {
             LOG.error("Error response from JPush server. Should review and fix it. ", e);
             e.printStackTrace();
         }
            return map;
     }
}

到这里已经基本结束现在来编写测试类。
推送模块测试

 Map<String, String> parm = new HashMap<>();
        parm.put("msg", "收到请联系管理员李洋");
        parm.put("title", "title");
        parm.put("alias","alias");     
        parm.put("tags","tags");
        parm.put("id","regid");
        JPushUtil.jpushAndroid(parm);

推送成功显示如下极光推送官网也会有推送记录:
jPush极光推送 测试demo以及绑定regid/标签/别名
jPush极光推送 测试demo以及绑定regid/标签/别名

下面来测试绑定

       clientService.bindMobile("自己手机号");
        //clientService.bindAlias("别名",set);
        //clientService.bindTags("标签",set);
        //clientService.clearTags();
        //clientService.unbindAlias();
        //clientService.changeTags();
        //clientService.unbindMobile();
        clientService.dgetInfo();
        //clientService.hasMobile();

测试结果
jPush极光推送 测试demo以及绑定regid/标签/别名
到这里全部结束 欢迎来讨论。

上一篇:泛型


下一篇:delphi 取上级目录