极光推送工具类

 本文主要介绍对接对接极光推送,包括发送自定义消息等。需要的朋友可以参考一下。

1.springboot对接极光推送,pom文件增加如下配置:

<dependency>

  <groupId>cn.jpush.api</groupId>

  <artifactId>jpush-client</artifactId>

  <version>3.4.7</version>

</dependency>

2.springboot对接application配置:

jpush:

  appKey: 您的appKey

  masterSecret: 您的masterSecret

  liveTime: 1000

  apnsProduction: true # 是否生成环境,true表示生成环境

3.JpushServiceImpl工具类

@Service

@Slf4j

public class JpushServiceImpl {

@Resource

    JPushProperties jpushConfig;

/**

    * 发送自定义消息,由APP端拦截信息后再决定是否创建通知(目前APP用此种方式)

*

    * @param title    App通知栏标题

    * @param content  App通知栏内容(为了单行显示全,尽量保持在22个汉字以下)

    * @param extrasMap 额外推送信息(不会显示在通知栏,传递数据用)

    * @param alias    别名数组,设定哪些用户手机能接收信息(为空则所有用户都推送)

    * @return PushResult

*/

    public PushResult sendCustomPush(String title,String content,Map extrasMap,String... alias)throws APIConnectionException,APIRequestException {

ClientConfig clientConfig =ClientConfig.getInstance();

clientConfig.setTimeToLive(Long.parseLong(jpushConfig.getLiveTime()));

clientConfig.setApnsProduction(jpushConfig.isApnsProduction());

// 使用NativeHttpClient网络客户端,连接网络的方式,不提供回调函数

        JPushClient jpushClient =new JPushClient(jpushConfig.getMasterSecret(),jpushConfig.getAppkey(),null,

clientConfig);

// 设置为消息推送方式为仅推送消息,不创建通知栏提醒

//        PushPayload payload = buildCustomPushPayload(title, content, extrasMap, alias);

        PushPayload payload = buildCustomPushPayload(title, content, extrasMap, alias);

PushResult result =jpushClient.sendPush(payload);

return result;

}

/**

    * 发送通知消息

    *

    * @param title    App通知栏标题

    * @param content  App通知栏内容(为了单行显示全,尽量保持在22个汉字以下)

    * @param extrasMap 额外推送信息(不会显示在通知栏,传递数据用)

    * @param alais    标签数组,设定哪些用户手机能接收信息(为空则所有用户都推送)

    */

    public PushResult sendPush(String title,String content,Map extrasMap,String... alais)throws APIConnectionException,APIRequestException {

ClientConfig clientConfig =ClientConfig.getInstance();

clientConfig.setTimeToLive(Long.valueOf(jpushConfig.getLiveTime()));

clientConfig.setApnsProduction(jpushConfig.isApnsProduction());

// 使用NativeHttpClient网络客户端,连接网络的方式,不提供回调函数

        JPushClient jpushClient =new JPushClient(jpushConfig.getMasterSecret(),jpushConfig.getAppkey(),null,

clientConfig);

// 设置推送方式

        PushPayload payload = buildPushLoadByAlias(title, content, extrasMap, alais);

PushResult result =jpushClient.sendPush(payload);

return result;

}

/**

    * 异步请求推送方式

    * 使用NettyHttpClient,异步接口发送请求,通过回调函数可以获取推送成功与否情况

    *

    * @param title    通知栏标题

    * @param content  通知栏内容(为了单行显示全,尽量保持在22个汉字以下)

    * @param extrasMap 额外推送信息(不会显示在通知栏,传递数据用)

    * @param alias    需接收的用户别名数组(为空则所有用户都推送)

    */

    public void sendPushWithCallback(String title,String content,Map extrasMap,String... alias) {

ClientConfig clientConfig =ClientConfig.getInstance();

clientConfig.setTimeToLive(Long.valueOf(jpushConfig.getLiveTime()));

clientConfig.setApnsProduction(jpushConfig.isApnsProduction());

String host = (String)clientConfig.get(ClientConfig.PUSH_HOST_NAME);

NettyHttpClient client =new NettyHttpClient(

ServiceHelper.getBasicAuthorization(jpushConfig.getAppkey(),jpushConfig.getMasterSecret()),null,

clientConfig);

try {

URI uri =new URI(host +clientConfig.get(ClientConfig.PUSH_PATH));

PushPayload payload = buildPushPayload(title, content, extrasMap, alias);

client.sendRequest(HttpMethod.POST,payload.toString(),uri,new NettyHttpClient.BaseCallback() {

@Override

                public void onSucceed(ResponseWrapper responseWrapper) {

if (200 == responseWrapper.responseCode) {

log.info("极光推送成功");

}else {

log.info("极光推送失败,返回结果: " + responseWrapper.responseContent);

}

}

});

}catch (URISyntaxException e) {

e.printStackTrace();

}finally {

// 需要手动关闭Netty请求进程,否则会一直保留

            client.close();

}

}

/**

    * 设置、更新、设备的 tag, alias 信息。

    *

    * @param registrationId 设备的registrationId

    * @param alias          更新设备的别名属性

    * @param tagsToAdd      添加设备的tag属性

    * @param tagsToRemove  移除设备的tag属性

    */

    public void UpdateDeviceTagAlias(String registrationId,String alias,Set tagsToAdd,Set tagsToRemove)throws APIConnectionException,APIRequestException {

JPushClient jpushClient =new JPushClient(jpushConfig.getMasterSecret(),jpushConfig.getAppkey());

jpushClient.updateDeviceTagAlias(registrationId, alias, tagsToAdd, tagsToRemove);

}

/**

    * 构建Android和IOS的推送通知对象

    *

* @return PushPayload

*/

    private PushPayload buildPushPayload(String title,String content,Map extrasMap,String... alias) {

if (extrasMap ==null || extrasMap.isEmpty()) {

extrasMap =new HashMap();

}

// 批量删除数组中空元素

        String[]newAlias = removeArrayEmptyElement(alias);

return PushPayload.newBuilder().setPlatform(Platform.android_ios())

// 别名为空,全员推送;别名不为空,按别名推送

                .setAudience((null ==newAlias ||newAlias.length ==0) ?Audience.all() :Audience.alias(alias))

//                .setAudience(Audience.registrationId("d"))

                .setNotification(Notification.newBuilder().setAlert(content)

.addPlatformNotification(

AndroidNotification.newBuilder().setTitle(title).addExtras(extrasMap).build())

.addPlatformNotification(IosNotification.newBuilder().incrBadge(1).addExtras(extrasMap).build())

.build())

.build();

}

/**

    * 根据标签推送相应的消息

    * @param title 推送消息标题

    * @param content 推送消息内容

    * @param map 推送额外信息

    * @param alias 推送的目标标签

    * @return

*/

    public PushPayload buildPushLoadByAlias(String title,String content,Map map,String... alias) {

if(map.isEmpty()){

map =new HashMap<>();

}

//批量删除数组中的空元素

//        String[] newTags = removeArrayEmptyElement(tags);

        String[]newAlias = removeArrayEmptyElement(alias);

return PushPayload.newBuilder()

//设置推送平台为安卓

                .setPlatform(Platform.android_ios())

//设置标签

                .setAudience((null ==newAlias ||newAlias.length ==0) ?Audience.all() :Audience.alias(alias))

//设置 推送的标签标题

                // 设置通知方式(以alert方式提醒)

                .setNotification(Notification.newBuilder().setAlert(content)

.addPlatformNotification(AndroidNotification.newBuilder().setTitle(title).addExtras(map).build()).build())

//sendno int 可选 推送序号 纯粹用来作为 API 调用标识

                //离线消息保留时长 推送当前用户不在线时,为该用户保留多长时间的离线消息(默认 86400 (1 天),最长 10 天。设置为 0 表示不保留离线消息,只有推送当前在线的用户可以收到)

                //apns_production boolean 可选 APNs是否生产环境  True 表示推送生产环境,False 表示要推送开发环境; 如果不指定则为推送生产环境

                //big_push_duration int 可选 定速推送时长(分钟) 又名缓慢推送,把原本尽可能快的推送速度,降低下来,在给定的 n 分钟内,均匀地向这次推送的目标用户推送。最大值为 1440。未设置则不是定速推送

//            .setOptions(Options.newBuilder().setApnsProduction(false).setTimeToLive(8600).setBigPushDuration(1).build())

                //设置通知内容

//            .setMessage(Message.newBuilder().setTitle("").setMsgContent("").setContentType("").build())

                .build();

}

/**

    * 构建Android和IOS的自定义消息的推送消息对象

    *

* @return PushPayload

*/

    private PushPayload buildCustomPushPayload(String title,String content,Map extrasMap,String... alias) {

// 批量删除数组中空元素

        String[]newAlias = removeArrayEmptyElement(alias);

return PushPayload.newBuilder().setPlatform(Platform.android_ios())

.setAudience((null ==newAlias ||newAlias.length ==0) ?Audience.all() :Audience.alias(alias))

.setNotification(Notification.newBuilder().setAlert(content)

.addPlatformNotification(AndroidNotification.newBuilder().setTitle(title).addExtras(extrasMap).build()).build())

//  .setMessage(Message.newBuilder().setTitle(title).setMsgContent(content).addExtras(extrasMap).build())

                .build();

}

/**

    * 发送自定义消息,由APP端拦截信息后再决定是否创建通知(目前APP用此种方式)

*

    * @param title    App通知栏标题

    * @param content  App通知栏内容(为了单行显示全,尽量保持在22个汉字以下)

    * @param extrasMap 额外推送信息(不会显示在通知栏,传递数据用)

    * @param alias    别名数组,设定哪些用户手机能接收信息(为空则所有用户都推送)

    * @return PushResult

*/

    public PushResult sendCustomPushByAlias(String notify_title,String title,String content,Map extrasMap,String... alias)throws APIConnectionException,APIRequestException {

ClientConfig clientConfig =ClientConfig.getInstance();

clientConfig.setTimeToLive(Long.parseLong(jpushConfig.getLiveTime()));

clientConfig.setApnsProduction(jpushConfig.isApnsProduction());

// 使用NativeHttpClient网络客户端,连接网络的方式,不提供回调函数

        JPushClient jpushClient =new JPushClient(jpushConfig.getMasterSecret(),jpushConfig.getAppkey(),null,

clientConfig);

// 设置为消息推送方式为仅推送消息,不创建通知栏提醒

//        PushPayload payload = buildCustomPushPayload(title, content, extrasMap, alias);

        PushPayload payload = buildPushObject_all_alias_alertWithTitle(notify_title,title, content, extrasMap,alias);

PushResult result =jpushClient.sendPush(payload);

return result;

}

/**

    * 推送自定义消息 指定别名推送

    * @param alias

    * @param notification_title

    * @param msg_title

    * @param msg_content

    * @param extrasMap

    * @return

*/

    private PushPayload buildPushObject_all_alias_alertWithTitle(String notification_title,String msg_title,String msg_content,Map extrasMap,String... alias) {

//创建一个IosAlert对象,可指定APNs的alert、title等字段

        //IosAlert iosAlert =  IosAlert.newBuilder().setTitleAndBody("title", "alert body").build();

        String[]newAlias = removeArrayEmptyElement(alias);

return PushPayload.newBuilder()

//指定要推送的平台,all代表当前应用配置了的所有平台,也可以传android等具体平台

                .setPlatform(Platform.all())

//指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id

                .setAudience((null ==newAlias ||newAlias.length ==0) ?Audience.all() :Audience.alias(alias))

//.setAudience(Audience.all()) //所有人

                //.setAudience(Audience.registrationId(registrationId)) //注册ID

                //jpush的通知,android的由jpush直接下发,iOS的由apns服务器下发,Winphone的由mpns下发

//                .setNotification(Notification.newBuilder()

//                        //指定当前推送的android通知

//                        .addPlatformNotification(AndroidNotification.newBuilder()

//                                .setAlert(msg_content)

//                                .setTitle(notification_title)

//                                //此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)

//                                .addExtras(extrasMap)

//                                .build())

//                        //指定当前推送的iOS通知

//                        .addPlatformNotification(IosNotification.newBuilder()

//                                //传一个IosAlert对象,指定apns title、title、subtitle等

//                                .setAlert(msg_content)

//                                //直接传alert

//                                //此项是指定此推送的badge自动加1

//                                .incrBadge(1)

//                                //此字段的值default表示系统默认声音;传sound.caf表示此推送以项目里面打包的sound.caf声音来提醒,

//                                // 如果系统没有此音频则以系统默认声音提醒;此字段如果传空字符串,iOS9及以上的系统是无声音提醒,以下的系统是默认声音

//                                .setSound("sound.caf")

//                                //此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)

//                                .addExtras(extrasMap)

//                                //此项说明此推送是一个background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification

//                                //取消此注释,消息推送时ios将无法在锁屏情况接收

//                                // .setContentAvailable(true)

//                                .build())

//                        .build())

                //Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,

                // sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的

                // [通知与自定义消息有什么区别?]了解通知和自定义消息的区别

                .setMessage(Message.newBuilder()

.setMsgContent(msg_content)

.setTitle(msg_title)

.addExtras(extrasMap)

//.addExtra("url", extrasparam) //释放该字段会发送两次消息,第二次消息内容是扩展字段

                        .build())

.setOptions(Options.newBuilder()

//此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义

                        .setApnsProduction(true)

//此字段是给开发者自己给推送编号,方便推送者分辨推送记录

                        .setSendno(1)

//此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天; 秒为单位

                        .setTimeToLive(1 *60 *60 *24)

.build())

.build();

}

/**

    * 删除别名中的空元素(需删除如:null,""," ")

    *

    * @param strArray

    * @return String[]

*/

    private String[]removeArrayEmptyElement(String... strArray) {

if (null == strArray || strArray.length ==0) {

return null;

}

ListtempList =Arrays.asList(strArray);

ListstrList =new ArrayList();

Iteratoriterator =tempList.iterator();

while (iterator.hasNext()) {

String str =iterator.next();

// 消除空格后再做比较

            if (null !=str && !"".equals(str.trim())) {

strList.add(str);

}

}

// 若仅输入"",则会将数组长度置为0

        String[]newStrArray =strList.toArray(new String[strList.size()]);

return newStrArray;

}

}

4.JPushProperties配置

@Component

@ConfigurationProperties(prefix ="jpush")

@Data

public class JPushProperties {

/**

    * 极光推送应用key

*/

    private String appkey;

/**

    * 极光推送的密码

    */

    private String masterSecret;

/**

    * 极光推送设置过期时间

    */

    private String liveTime;

private String adminUserId;

private boolean apnsProduction;

public boolean isApnsProduction() {

return apnsProduction;

}

public void setApnsProduction(boolean apnsProduction) {

this.apnsProduction = apnsProduction;

}

public String getAdminUserId() {

return adminUserId;

}

public void setAdminUserId(String adminUserId) {

this.adminUserId = adminUserId;

}

public String getAppkey() {

return appkey;

}

public void setAppkey(String appkey) {

this.appkey = appkey;

}

public String getMasterSecret() {

return masterSecret;

}

public void setMasterSecret(String masterSecret) {

this.masterSecret = masterSecret;

}

public String getLiveTime() {

return liveTime;

}

public void setLiveTime(String liveTime) {

this.liveTime = liveTime;

}

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 所选依赖: 工具类:一、 package com.xxx.core.util.push.enums; /** 配置...
    Y_LY阅读 1,907评论 0 2
  • package com.jpxx.jpwgh.util; import net.sf.json.JSONObjec...
    蛋皮皮652阅读 333评论 0 0
  • 前言 如果你还没有搭建极光推送服务器,建议你根据情况,先从服务器搭建开始。 前文标题: 《【极光推送】jpush服...
    左岸花不开阅读 11,183评论 1 6
  • 应用场景:在我们的项目中我们用的是创建视频会议和预警消息通知推送这两种情况,首先创建视频会议和中途邀请人参加会议我...
    蛋皮皮652阅读 3,687评论 1 2
  • 前提 之前接触的极光推送都是关于移动端的推送,服务器端的推送没有接触过,另外关于Spring boot,如何集成也...
    Silence潇湘夜雨阅读 2,574评论 0 4