前言
- 先前專案中用的推送時騰訊的信鴿推送,總是存在很多問題,現在改為極光,記錄下,java的推送工具類
程式碼
/**
* 指定註冊Id傳送
*
* @param pushPKId 儲存的推送表記錄主鍵id
* @param jpushRegId 註冊ID
* @param type 型別
* @param jsonObject 需要app裡處理的資料
*/
private static boolean androidSendPush(final String pushPKId,final String jpushRegId, final String type, final JsonObject jsonObject) {
logger.debug("jpushRegId:"+jpushRegId + ", type:"+type+", data:"+(jsonObject != null ? jsonObject.toString() : "{}"));
ClientConfig clientConfig = ClientConfig.getInstance();
JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
PushPayload payload = buildPushAndroid(pushPKId,jpushRegId, type, getTypeMap().get(type), jsonObject);
try {
PushResult result = jpushClient.sendPush(payload);
logger.info("Jpush Got result - " + result);
return true;
} catch (APIConnectionException e) {
logger.error("Connection error. Should retry later. ", e);
return false;
} 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());
logger.info("Msg ID: " + e.getMsgId());
return false;
}
}
/**
* 構造PushPayload
*
* @param pushPkID 儲存的推送表id
* @param jpushRegId
* @param type
* @param jsonObject
* @return
*/
private static PushPayload buildPushAndroid(String pushPkID,final String jpushRegId, final String type, final String msgContent, final JsonObject jsonObject) {
return PushPayload.newBuilder()
.setPlatform(Platform.android())
.setAudience(Audience.registrationId(jpushRegId))
.setMessage(Message.newBuilder()
.setMsgContent(msgContent)
.addExtra("msgType", type)
.addExtra("msgContent", jsonObject != null ? jsonObject.toString() : "{}" )
.addExtra("knTchgId", pushPkID)
.build())
.setOptions(Options.newBuilder()
.setApnsProduction(true)
.build())
.build();
}
/**
* 獲取push推送描述
*
* @return
*/
private static Map<String,String> getTypeMap(){
typeMap.put(PUSH_TYPE_BILL_, "您有一條新的待收集訂單");
typeMap.put(PUSH_TYPE_TRANSFER_, "您有一條USERNAME轉交的訂單");
typeMap.put(PUSH_TYPE_DRIVER_CONFIRM_, "您有一條出庫單待確認");
return typeMap;
}