java整合极光推送
本文讲的是java整合极光JPush进行消息推送。
一、导包
<!-- 极光推送 -->
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jpush-client</artifactId>
<version>3.5.1</version>
</dependency>
<!-- jPush公共封装开发包 -->
<dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jiguang-common</artifactId>
<version>1.1.11</version>
</dependency>
二、推送示例
1、推送代码
/**
* @Anthor zyl
* 推送工具类
* @Date 2021/8/9
**/
@Slf4j
@Service
public class PushSendService {
@Value("${app_key}")
private String appKey;
@Value("${master_secret}")
private String masterSecret;
@Value("${group_push_key}")
private String groupPushKey;
@Value("${group_master_secret}")
private String groupMasterSecret;
public static final String TITLE = "Test from API example";
public static final String ALERT = "Test from API Example - alert";
public static final String MSG_CONTENT = "Test from API Example - msgContent";
public static final String REGISTRATION_ID = "0900e8d85ef";
public static final String TAG = "tag_api";
public static long sendCount = 0;
private static long sendTotalTime = 0;
// 使用 NettyHttpClient 异步接口发送请求
public void testSendPushWithCallback() {
ClientConfig clientConfig = ClientConfig.getInstance();
String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME);
final NettyHttpClient client = new NettyHttpClient(ServiceHelper.getBasicAuthorization(appKey, masterSecret),
null, clientConfig);
try {
URI uri = new URI(host + clientConfig.get(ClientConfig.PUSH_PATH));
PushPayload payload = buildPushObject_all_alias_alert();
client.sendRequest(HttpMethod.POST, payload.toString(), uri, new NettyHttpClient.BaseCallback() {
@Override
public void onSucceed(ResponseWrapper responseWrapper) {
log.info("Got result: " + responseWrapper.responseContent);
}
});
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
public boolean sendPush(Audience audience, String title, String content) {
ClientConfig clientConfig = ClientConfig.getInstance();
final JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
final PushPayload payload = PushPayload.newBuilder()
.setPlatform(Platform.android_ios())
.setAudience(audience)
.setNotification(Notification.android(content, title, null))
.build();
// PushPayload payload = buildPushObject_all_alias_alert();
try {
PushResult result = jpushClient.sendPush(payload);
log.info("推送结果:" + JSON.toJSONString(result));
} catch (APIConnectionException e) {
log.error("Connection error. Should retry later. ", e);
log.error("Sendno: " + payload.getSendno());
return false;
} catch (APIRequestException e) {
StringBuffer sb = new StringBuffer();
// log.error("Error response from JPush server. Should review and fix it. ", e);
sb.append("\n-------------------发送jPush消息失败-------------------");
sb.append("\noperate:" + title);
sb.append("\nHTTP Status: " + e.getStatus());
sb.append("\nError Code: " + e.getErrorCode());
sb.append("\nError Message: " + e.getErrorMessage());
sb.append("\nMsg ID: " + e.getMsgId());
sb.append("\nSendno: " + payload.getSendno());
sb.append("\n-------------------发送jPush消息失败-------------------");
log.info(sb.toString());
return false;
}
return true;
}
public void testSendPushWithEncrypt() {
ClientConfig clientConfig = ClientConfig.getInstance();
clientConfig.setEncryptType(EncryptKeys.ENCRYPT_SMS2_TYPE);
final JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
final PushPayload payload = buildPushObject_android_and_ios();
try {
PushResult result = jpushClient.sendPush(payload);
log.info("Got result - " + result);
System.out.println(result);
// 如果使用 NettyHttpClient,需要手动调用 close 方法退出进程
// If uses NettyHttpClient, call close when finished sending request, otherwise process will not exit.
// jpushClient.close();
} catch (APIConnectionException e) {
log.error("Connection error. Should retry later. ", e);
log.error("Sendno: " + payload.getSendno());
} 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("Msg ID: " + e.getMsgId());
log.error("Sendno: " + payload.getSendno());
}
}
public void testSendPush_fromJSON() {
ClientConfig clientConfig = ClientConfig.getInstance();
JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
Gson gson = new GsonBuilder()
.registerTypeAdapter(PlatformNotification.class, new InterfaceAdapter<PlatformNotification>())
.create();
String payloadString = "{\"platform\":{\"all\":false,\"deviceTypes\":[\"IOS\"]},\"audience\":{\"all\":true,\"targets\":[{\"audienceType\":\"TAG_AND\",\"values\":[\"tag1\",\"tag_all\"]}]},\"notification\":{\"notifications\":[{\"soundDisabled\":false,\"badgeDisabled\":false,\"sound\":\"happy\",\"badge\":\"5\",\"contentAvailable\":false,\"alert\":\"Test from API Example - alert\",\"extras\":{\"from\":\"JPush\"},\"type\":\"cn.jpush.api.push.model.notification.IosNotification\"}]},\"message\":{\"msgContent\":\"Test from API Example - msgContent\"},\"options\":{\"sendno\":1429488213,\"overrideMsgId\":0,\"timeToLive\":-1,\"apnsProduction\":true,\"bigPushDuration\":0}}";
PushPayload payload = gson.fromJson(payloadString, PushPayload.class);
try {
PushResult result = jpushClient.sendPush(payloadString);
log.info("Got result - " + result);
} catch (APIConnectionException e) {
log.error("Connection error. Should retry later. ", e);
// log.error("Sendno: " + payload.getSendno());
} 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("Msg ID: " + e.getMsgId());
//log.error("Sendno: " + payload.getSendno());
}
}
/**
* 测试多线程发送 2000 条推送耗时
*/
public void testSendPushes() {
ClientConfig clientConfig = ClientConfig.getInstance();
final JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, clientConfig);
String authCode = ServiceHelper.getBasicAuthorization(appKey, masterSecret);
NativeHttpClient httpClient = new NativeHttpClient(authCode, null, clientConfig);
jpushClient.getPushClient().setHttpClient(httpClient);
final PushPayload payload = buildPushObject_ios_tagAnd_alertWithExtrasAndMessage();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread() {
public void run() {
for (int j = 0; j < 200; j++) {
long start = System.currentTimeMillis();
try {
PushResult result = jpushClient.sendPush(payload);
log.info("Got result - " + result);
} catch (APIConnectionException e) {
log.error("Connection error. Should retry later. ", e);
log.error("Sendno: " + payload.getSendno());
} 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("Msg ID: " + e.getMsgId());
log.error("Sendno: " + payload.getSendno());
}
System.out.println("耗时" + (System.currentTimeMillis() - start) + "毫秒 sendCount:" + (++sendCount));
}
}
};
thread.start();
}
}
public void testSendGroupPush() {
GroupPushClient groupPushClient = new GroupPushClient(groupMasterSecret, groupPushKey);
final PushPayload payload = buildPushObject_android_and_ios();
try {
GroupPushResult groupPushResult = groupPushClient.sendGroupPush(payload);
Map<String, PushResult> result = groupPushResult.getAppResultMap();
for (Map.Entry<String, PushResult> entry : result.entrySet()) {
PushResult pushResult = entry.getValue();
PushResult.Error error = pushResult.error;
if (error != null) {
log.info("AppKey: " + entry.getKey() + " error code : " + error.getCode() + " error message: " + error.getMessage());
} else {
log.info("AppKey: " + entry.getKey() + " sendno: " + pushResult.sendno + " msg_id:" + pushResult.msg_id);
}
}
} catch (APIConnectionException e) {
log.error("Connection error. Should retry later. ", e);
log.error("Sendno: " + payload.getSendno());
} 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("Msg ID: " + e.getMsgId());
log.error("Sendno: " + payload.getSendno());
}
}
public static PushPayload buildPushObject_all_all_alert() {
return PushPayload.alertAll(ALERT);
}
public static PushPayload buildPushObject_all_alias_alert() {
return PushPayload.newBuilder()
.setPlatform(Platform.all())
.setAudience(Audience.alias("alias1"))
.setNotification(Notification.alert(ALERT))
.build();
}
public static PushPayload buildPushObject_android_tag_alertWithTitle() {
return PushPayload.newBuilder()
.setPlatform(Platform.android())
.setAudience(Audience.tag("tag1"))
.setNotification(Notification.android(ALERT, TITLE, null))
.build();
}
public static PushPayload buildPushObject_android_and_ios() {
Map<String, String> extras = new HashMap<String, String>();
extras.put("test", "https://community.jiguang.cn/push");
return PushPayload.newBuilder()
.setPlatform(Platform.android_ios())
.setAudience(Audience.all())
.setNotification(Notification.newBuilder()
.setAlert("testing alert content")
.addPlatformNotification(AndroidNotification.newBuilder()
.setTitle("Android Title")
.addExtras(extras).build())
.addPlatformNotification(IosNotification.newBuilder()
.incrBadge(1)
.addExtra("extra_key", "extra_value").build())
.addVoip("key", "value")
.addVoip("key2", 2)
.addVoip("key3", true)
.build())
.setOptions(Options.newBuilder()
.setApnsProduction(false)
.setTimeToLive(43200)
.build())
.build();
}
public void buildPushObject_with_extra() {
JsonObject jsonExtra = new JsonObject();
jsonExtra.addProperty("extra1", 1);
jsonExtra.addProperty("extra2", false);
Map<String, String> extras = new HashMap<String, String>();
extras.put("extra_1", "val1");
extras.put("extra_2", "val2");
PushPayload payload = PushPayload.newBuilder()
.setPlatform(Platform.android_ios())
.setAudience(Audience.tag("tag1"))
.setNotification(Notification.newBuilder()
.setAlert("alert content")
.addPlatformNotification(AndroidNotification.newBuilder()
.setTitle("Android Title")
.addExtras(extras)
.addExtra("booleanExtra", false)
.addExtra("numberExtra", 1)
.addExtra("jsonExtra", jsonExtra)
.build())
.addPlatformNotification(IosNotification.newBuilder()
.incrBadge(1)
.addExtra("extra_key", "extra_value").build())
.build())
.build();
System.out.println(payload.toJSON());
}
public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage() {
JsonObject sound = new JsonObject();
sound.add("critical", new JsonPrimitive(1));
sound.add("name", new JsonPrimitive("default"));
sound.add("volume", new JsonPrimitive(0.2));
return PushPayload.newBuilder()
.setPlatform(Platform.ios())
.setAudience(Audience.tag_and("tag1", "tag_all"))
.setNotification(Notification.newBuilder()
.addPlatformNotification(IosNotification.newBuilder()
.setAlert(ALERT)
.setBadge(5)
.setMutableContent(false)
.setSound(sound)
.addExtra("from", "JPush")
.build())
.build())
.setMessage(Message.content(MSG_CONTENT))
.setOptions(Options.newBuilder()
.setApnsProduction(true)
.build())
.build();
}
public static PushPayload buildPushObject_android_newly_support() {
JsonObject inbox = new JsonObject();
inbox.add("line1", new JsonPrimitive("line1 string"));
inbox.add("line2", new JsonPrimitive("line2 string"));
inbox.add("contentTitle", new JsonPrimitive("title string"));
inbox.add("summaryText", new JsonPrimitive("+3 more"));
JsonObject intent = new JsonObject();
intent.add("url", new JsonPrimitive("intent:#Intent;component=com.jiguang.push/com.example.jpushdemo.SettingActivity;end"));
Notification notification = Notification.newBuilder()
.addPlatformNotification(AndroidNotification.newBuilder()
.setAlert(ALERT)
.setBigPicPath("path to big picture")
.setBigText("long text")
.setBuilderId(1)
.setCategory("CATEGORY_SOCIAL")
.setInbox(inbox)
.setStyle(1)
.setTitle("Alert test")
.setPriority(1)
.setLargeIcon("http://www.jiguang.cn/largeIcon.jpg")
.setIntent(intent)
.build())
.build();
return PushPayload.newBuilder()
.setPlatform(Platform.all())
.setAudience(Audience.all())
.setNotification(notification)
.setOptions(Options.newBuilder()
.setApnsProduction(true)
.setSendno(ServiceHelper.generateSendno())
.build())
.build();
}
public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {
return PushPayload.newBuilder()
.setPlatform(Platform.android_ios())
.setAudience(Audience.newBuilder()
.addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))
.addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
.build())
.setMessage(Message.newBuilder()
.setMsgContent(MSG_CONTENT)
.addExtra("from", "JPush")
.build())
.build();
}
public static PushPayload buildPushObject_all_tag_not() {
return PushPayload.newBuilder()
.setPlatform(Platform.all())
.setAudience(Audience.tag_not("abc", "123"))
.setNotification(Notification.alert(ALERT))
.build();
}
public static PushPayload buildPushObject_android_cid() {
Collection<String> list = new LinkedList<String>();
list.add("1507bfd3f79558957de");
list.add("1507bfd3f79554957de");
list.add("1507bfd3f79555957de");
list.add("1507bfd3f79556957de");
list.add("1507ffd3f79545957de");
list.add("1507ffd3f79457957de");
list.add("1507ffd3f79456757de");
return PushPayload.newBuilder()
.setPlatform(Platform.android())
.setAudience(Audience.registrationId(list))
.setNotification(Notification.alert(ALERT))
.setCid("cid")
.build();
}
public void testSendPushWithCustomConfig() {
ClientConfig config = ClientConfig.getInstance();
config.setPushHostName("https://api.jpush.cn");
JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, config);
PushPayload payload = buildPushObject_all_all_alert();
try {
PushResult result = jpushClient.sendPush(payload);
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("Msg ID: " + e.getMsgId());
}
}
public void testSendIosAlert() {
JPushClient jpushClient = new JPushClient(masterSecret, appKey);
IosAlert alert = IosAlert.newBuilder()
.setTitleAndBody("test alert", "subtitle", "test ios alert json")
.setActionLocKey("PLAY")
.build();
try {
PushResult result = jpushClient.sendIosNotificationWithAlias(alert, new HashMap<String, String>(), "alias1");
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());
}
}
public void testSendWithSMS() {
JPushClient jpushClient = new JPushClient(masterSecret, appKey);
try {
SMS sms = SMS.newBuilder()
.setDelayTime(1000)
.setTempID(2000)
.addPara("Test", 1)
.setActiveFilter(false)
.build();
PushResult result = jpushClient.sendAndroidMessageWithAlias("Test SMS", "test sms", sms, "alias1");
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());
}
}
public void testGetCidList() {
JPushClient jPushClient = new JPushClient(masterSecret, appKey);
try {
CIDResult result = jPushClient.getCidList(3, "push");
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());
}
}
public void testSendPushWithCid() {
JPushClient jPushClient = new JPushClient(masterSecret, appKey);
PushPayload pushPayload = buildPushObject_android_cid();
try {
PushResult result = jPushClient.sendPush(pushPayload);
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());
}
}
/**
* 批量单推接口
* https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/#vip
*/
public void testBatchSend() {
JPushClient jPushClient = new JPushClient(masterSecret, appKey);
try {
{
List<PushPayload> pushPayloadList = new ArrayList<>();
PushPayload.Builder builder1 = PushPayload.newBuilder();
builder1.setMessage(Message.content("content1 by alias"))
.setNotification(Notification.alert(ALERT))
.setPlatform(Platform.all())
.setAudience(Audience.all())
.setOptions(Options.sendno())
.setTarget("1507ffd3f79456757de");
pushPayloadList.add(builder1.build());
PushPayload.Builder builder2 = PushPayload.newBuilder();
builder2.setMessage(Message.content("content2 by alias"))
.setNotification(Notification.alert(ALERT))
.setPlatform(Platform.android())
.setAudience(Audience.all())
.setOptions(Options.sendno())
.setTarget("1507ffd3f79456757de");
pushPayloadList.add(builder2.build());
BatchPushResult result = jPushClient.batchSendPushByAlias(pushPayloadList);
log.info("batchSendPushByAlias param: {}, result: {}", pushPayloadList, new Gson().toJson(result.getBatchPushResult()));
}
{
List<PushPayload> pushPayloadList = new ArrayList<>();
PushPayload.Builder builder1 = PushPayload.newBuilder();
builder1.setMessage(Message.content("content1 by regId"))
.setNotification(Notification.alert(ALERT))
.setPlatform(Platform.android())
.setAudience(Audience.all())
.setOptions(Options.sendno())
.setTarget("1507ffd3f79456757de");
pushPayloadList.add(builder1.build());
PushPayload.Builder builder2 = PushPayload.newBuilder();
builder2.setMessage(Message.content("content2 by regId"))
.setNotification(Notification.alert(ALERT))
.setAudience(Audience.all())
.setPlatform(Platform.ios())
.setOptions(Options.sendno())
.setTarget("1507ffd3f79456757de");
pushPayloadList.add(builder2.build());
BatchPushResult result = jPushClient.batchSendPushByRegId(pushPayloadList);
log.info("batchSendPushByRegId param: {}, result: {}", pushPayloadList, new Gson().toJson(result.getBatchPushResult()));
}
} 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());
}
}
/**
* 自定义发送参数名称, 华为客户可参考该方法
*/
public void testSendPushWithCustomField() {
ClientConfig config = ClientConfig.getInstance();
// Setup the custom hostname
config.setPushHostName("https://api.jpush.cn");
JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, config);
Notification notification = Notification.newBuilder()
.addPlatformNotification(AndroidNotification.newBuilder()
.setAlert(ALERT)
.setTitle("Alert test")
.setLargeIcon("http://www.jiguang.cn/largeIcon.jpg")
.addCustom("uri_activity", "uri_activity")
.addCustom("uri_flag", "uri_flag")
.addCustom("uri_action", "uri_action")
.build())
.build();
PushPayload.Builder payloadBuilder = new PushPayload.Builder()
.setPlatform(Platform.all())
.setAudience(Audience.all())
.setNotification(notification);
try {
PushResult result = jpushClient.sendPush(payloadBuilder.build());
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("Msg ID: " + e.getMsgId());
}
}
/**
* 回调参数示例
*/
public void testSendPushWithCustom() {
ClientConfig config = ClientConfig.getInstance();
// Setup the custom hostname
config.setPushHostName("https://api.jpush.cn");
JPushClient jpushClient = new JPushClient(masterSecret, appKey, null, config);
Notification notification = Notification.newBuilder()
.addPlatformNotification(AndroidNotification.newBuilder()
.setAlert(ALERT)
.setTitle("Alert test")
.build())
.build();
JsonObject callback = new JsonObject();
callback.addProperty("url", "https://www.jiguagn.cn/callback");
JsonObject params = new JsonObject();
params.addProperty("name", "joe");
params.addProperty("age", 26);
callback.add("params", params);
callback.addProperty("type", 3);
PushPayload.Builder payloadBuilder = new PushPayload.Builder()
.setPlatform(Platform.all())
.setAudience(Audience.all())
.setNotification(notification)
.addCustom("callback", callback);
try {
PushResult result = jpushClient.sendPush(payloadBuilder.build());
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("Msg ID: " + e.getMsgId());
}
}
}
其中appKey、masterSecret、groupPushKey、groupMasterSecret是去官网你的账户拿的。在上面众多方法中你只需要关注sendPush方法就够了。
二、推送示例
private void sendJpush(MessageRecord messageRecord){
String title = "推送测试";
String description = "你今天吃早餐了么?";
String operate = "alias";
List<String> list = Lists.newArrayList();
list.add("zz");
Audience audience = null;
//构造推送对象
if("alias".equalsIgnoreCase(operate)){
audience = Audience.alias(list);
}else{
audience = Audience.newBuilder()
.addAudienceTarget(AudienceTarget.tag(list))
.addAudienceTarget(AudienceTarget.tag_and(list))
.build();
}
//推送
boolean jPushResult = pushSendService.sendPush(audience, title, description);
}
alias是使用别名推送,tag是使用标签推送。上面示例中是推送给alias为zz的监听消息,这时候如果你的app监听了alias为zz的消息,那么就会收到这条推送。
三、总结
至于app怎么监听消息在我上一篇博文中有写道flutter整合极光推送。
谢谢各位!!!