日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > java >内容正文

java

Java极光推送工具类

發(fā)布時(shí)間:2023/12/10 java 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Java极光推送工具类 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一、使用步驟

目錄

1.引入架包

2.創(chuàng)建推送的對(duì)象類

3.創(chuàng)建Util類,運(yùn)行main測(cè)試完成


?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.創(chuàng)建推送的對(duì)象類

代碼如下(示例):

package com.example.demo2.util.jpush;import lombok.Data;import java.util.List;@Data public class PushStudent {/** 發(fā)送目標(biāo)類型 **/private Integer audienceType;/** 接收消息的用戶別名 **/private String aliasName;/** 標(biāo)題 **/private String title;/** 內(nèi)容 **/private String content;/** 跳轉(zhuǎn)類型 0:原生 1:網(wǎng)頁 **/private Integer goType;/** 跳轉(zhuǎn) pageKey **/private String pageKey;/** 推送類型id **/private Long pushTypeId;/** 跳轉(zhuǎn) url **/private String url;/** 學(xué)生編號(hào) **/private String studentCode;/** 發(fā)送學(xué)生消息id **/private Long pushStudentId;/** 發(fā)送目標(biāo) **/public enum AudienceTypeEnum {/** 所有用戶 **/all(0, "所有用戶"),/** 標(biāo)簽用戶 **/tags(1, "標(biāo)簽用戶"),/** 別名用戶 **/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.創(chuàng)建Util類,運(yùn)行main測(cè)試完成

代碼如下(示例):

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環(huán)境,false表示開發(fā),true表示生產(chǎn);對(duì)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;}/** 極光返回的狀態(tài)碼 **/private static Map<Integer, String> codeMap = new HashMap(12){private static final long serialVersionUID = 1L;{put(200,"OK Success!");put(400, "錯(cuò)誤的請(qǐng)求 該請(qǐng)求是無效的。相應(yīng)的描述信息會(huì)說明原因。");put(401, "未驗(yàn)證 沒有驗(yàn)證信息或者驗(yàn)證失敗");put(403, "被拒絕 理解該請(qǐng)求,但不被接受。相應(yīng)的描述信息會(huì)說明原因。");put(404, "無法找到 資源不存在,請(qǐng)求的用戶的不存在,請(qǐng)求的格式不被支持。");put(405, "請(qǐng)求方法不合適 該接口不支持該方法的請(qǐng)求。");put(410, "已下線 請(qǐng)求的資源已下線。請(qǐng)參考相關(guān)公告。");put(429, "過多的請(qǐng)求 請(qǐng)求超出了頻率限制。相應(yīng)的描述信息會(huì)解釋具體的原因。");put(500, "內(nèi)部服務(wù)錯(cuò)誤 服務(wù)器內(nèi)部出錯(cuò)了。請(qǐng)聯(lián)系我們盡快解決問題。");put(502, "無效代理 業(yè)務(wù)服務(wù)器下線了或者正在升級(jí)。請(qǐng)稍后重試。");put(503, "服務(wù)暫時(shí)失效 服務(wù)器無法響應(yīng)請(qǐng)求。請(qǐng)稍后重試。");put(504, "代理超時(shí)");}};public static String getCodeStr(int code){return (codeMap.get(code)==null || "".equals(codeMap.get(code)))?"無對(duì)應(yīng)狀態(tài)碼值":codeMap.get(code);}/** 獲取 cid,避免同一個(gè)通知被調(diào)用多次 **/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;}// 擴(kuò)展消息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())// 應(yīng)用角標(biāo).incrBadge(1).addExtras(getAppExtra(pushMessage)).setMutableContent(true).build();}/** 發(fā)送極光消息 **/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);// 設(shè)置發(fā)送設(shè)備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("消息標(biāo)題");mesVo.setContent("消息內(nèi)容消息內(nèi)容消息內(nèi)容");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());}}

總結(jié)

以上是生活随笔為你收集整理的Java极光推送工具类的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。