一、引入Maven jar 包
版本非實時更新,故可取官網或Maven倉庫尋找最新地址
https://mvnrepository.com/artifact/cn.jpush.api/jpush-client
<!-- 極光推送 -->
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jpush-client</artifactId>
<version>3.3.9</version>
</dependency>
二、配置yml文件
#極光推送服務
jpush:
appKey: fff8c1798d4dawdaw8a1fc7d #(示例,不可用)
masterSecret: d223479342347d4610a342427 #(示例,不可用)
三、參數封裝實體類
@Setter
@Getter
@ToString
/**
* 漂流瓶推送自定義消息接收參數實體類
* 加入了Lombok set、get、tostring註解 若無該插件請手動添加set、get、tostring方法
*/
public class CustomMessageDomain {
/** 設備標識 用戶ID 別名 */
private String alias;
/** 通知內容標題 */
private String notificationTitle;
/** 消息內容標題 */
private String msgTitle;
/** 消息內容 */
private String msgContent;
/** 擴展字段(通常傳跳轉的鏈接)*/
private String extrasParam;
}
四、接口方法
APPResponseDate爲封裝的方法返回值實體類。 可以選擇無返回的方法
@PostMapping("sendCustomMessage")
--Swagger註解可選可不選
@ApiOperation(value = "根據別名推送自定義消息 (別名爲手機號)", httpMethod = "POST")
@ApiImplicitParams({
@ApiImplicitParam(name = "alias", value = "設備標識 用戶ID 別名", required = true, paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "notificationTitle", value = "通知內容標題", required = true, paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "msgTitle", value = "消息內容標題", required = true, paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "msgContent", value = "消息內容", required = true, paramType = "query", dataType = "String"),
@ApiImplicitParam(name = "extrasParam", value = "擴展字段(通常傳跳轉的鏈接)非必傳", required = false, paramType = "query", dataType = "String")
})
--Swagger註解可選可不選
public AppResponseData sendCustomMessage(@RequestBody CustomMessageDomain customMessageDomain) {
//給指定別名的用戶推送一條自定義消息
PushUtil.getInstance().sendToRegistrationId(customMessageDomain.getAlias(),
customMessageDomain.getNotificationTitle(),
customMessageDomain.getMsgTitle(),
customMessageDomain.getMsgContent(),
customMessageDomain.getExtrasParam());
return new AppResponseData(ResultCode.SUCCESS, "推送成功!");
}
五、PushUtil 工具類
public class PushUtil {
private static PushUtil instance;
private JPushClient jpushClient;
//日誌記錄
private static Logger logger = LoggerFactory.getLogger(PushUtil.class);
/**
* 極光賬戶初始化
*/
private PushUtil() {
//這裏是賬戶 key 與masterSecret 建議從配置文件中讀取
String appKey = "*************";
String masterSecret = "*************";
if (appKey == null || masterSecret == null) {
throw new JPushException("極光推送賬戶初始化失敗");
}
jpushClient = new JPushClient(masterSecret, appKey);
}
public static PushUtil getInstance() {
if (null == instance) {
synchronized (PushUtil.class) {
if (null == instance) {
instance = new PushUtil();
}
}
}
return instance;
}
// Device===================================================
/**
* 推送給指定設備標識參數的用戶(自定義消息通知)
* @param alias 設備標識 用戶ID 別名
* @param notification_title 通知內容標題
* @param msg_title 消息內容標題
* @param msg_content 消息內容
* @param extrasparam 擴展字段(通常傳跳轉的鏈接)
* @return 0推送失敗,1推送成功
*/
public int sendToRegistrationId(String alias, String notification_title, String msg_title, String msg_content, String extrasparam) {
int result = 0;
try {
PushPayload pushPayload= this.buildPushObject_all_alias_alertWithTitle(alias, notification_title, msg_title, msg_content, extrasparam);
PushResult pushResult = jpushClient.sendPush(pushPayload);
if(pushResult.getResponseCode() == 200){
result=1;
}
logger.info("[極光推送]PushResult result is " + pushResult);
} catch (APIConnectionException e) {
logger.error("[極光推送]Connection error. Should retry later. ", e);
} catch (APIRequestException e) {
logger.error("[極光推送]Error response from JPush server. Should review and fix it. ", e);
logger.info("[極光推送]HTTP Status: " + e.getStatus());
logger.info("[極光推送]Error Code: " + e.getErrorCode());
logger.info("[極光推送]Error Message: " + e.getErrorMessage());
}
return result;
}
/**
* 推送自定義消息 指定別名推送
* @param alias
* @param notification_title
* @param msg_title
* @param msg_content
* @param extrasparam
* @return
*/
private PushPayload buildPushObject_all_alias_alertWithTitle(String alias, String notification_title, String msg_title, String msg_content, String extrasparam) {
//創建一個IosAlert對象,可指定APNs的alert、title等字段
//IosAlert iosAlert = IosAlert.newBuilder().setTitleAndBody("title", "alert body").build();
return PushPayload.newBuilder()
//指定要推送的平臺,all代表當前應用配置了的所有平臺,也可以傳android等具體平臺
.setPlatform(Platform.all())
//指定推送的接收對象,all代表所有人,也可以指定已經設置成功的tag或alias或該應應用客戶端調用接口獲取到的registration id
.setAudience(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)
.addExtra("url", extrasparam)
.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)
.addExtra("url", extrasparam)
//此項說明此推送是一個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)
//.addExtra("url", extrasparam) //釋放該字段會發送兩次消息,第二次消息內容是擴展字段
.build())
.setOptions(Options.newBuilder()
//此字段的值是用來指定本推送要推送的apns環境,false表示開發,true表示生產;對android和自定義消息無意義
.setApnsProduction(true)
//此字段是給開發者自己給推送編號,方便推送者分辨推送記錄
.setSendno(1)
//此字段的值是用來指定本推送的離線保存時長,如果不傳此字段則默認保存一天,最多指定保留十天; 秒爲單位
.setTimeToLive(1 * 60 * 60 * 24)
.build())
.build();
}
}
六、完成
調用該接口,Android或者IOS端即可收到一條自定義消息。