当前位置:   article > 正文

java-极光推送(服务端)_极光推送java

极光推送java

目录

一.极光简介

1.极光官网地址

2.极光api地址

3.极光SDK下载地址

4.内容介绍

推送人群(Audience)

二.代码

1.导入依赖

2.极光推送工具类

1.一类

2.二类

3.三类


一.极光简介

1.极光官网地址

注册登录   应用管理创建应用进入应用设置  获取服务端需要用到AppKeyMaster Secret

极光推送-中国领先的客户互动和营销科技服务商,助力企业运营、增长和变现极光基于海量数据为移动开发者提供消息推送、一键认证、短信发送、即时通讯、数据统计、统一消息系统等服务,以及一站式流量接入、行业应用的运营解决方案,助力企业运营、增长和变现.https://www.jiguang.cn/

2.极光api地址

极光文档极光文档,极光开发者文档https://docs.jiguang.cn/jpush/server/push/server_overview

3.极光SDK下载地址

极光文档极光文档,极光开发者文档https://docs.jiguang.cn/jpush/resources

4.内容介绍

推送平台

JPush 当前支持 Android, iOS, QuickApp,Windows Phone 四个平台的推送。其关键字分别为:"android", "ios", "quickapp"。

如果目标平台为 iOS 平台,推送 Notification 时需要在 options 中通过 apns_production 字段来设定推送环境。True 表示推送生产环境,False 表示要推送开发环境; 如果不指定则为推送生产环境;一次只能推送给一个环境。

推送目标:广播(所有用户)、alias(别名:用别名来标识一个用户)、tag(标签:用标签来进行大规模的设备属性、用户属性分群。 一次推送最多 20 个)等。

推送方式:通知、自定义消息,富媒体和本地通知。

  • 通知

或者说 Push Notification,即指在手机的通知栏(状态栏)上会显示的一条通知信息。 通知主要用来达到提示用户的目的,应用于新闻内容、促销活动、产品信息、版本更新提醒、订单状态提醒等多种场景

  • 自定义消息

自定义消息不是通知,所以不会被 SDK 展示到通知栏上。其内容完全由开发者自己定义。 自定义消息主要用于应用的内部业务逻辑。一条自定义消息推送过来,有可能没有任何界面显示。

  • 本地通知

本地通知 API 不依赖于网络,无网条件下依旧可以触发;本地通知的定时时间是自发送时算起的,不受中间关机等操作的影响。 本地通知与网络推送的通知是相互独立的,不受保留最近通知条数上限的限制。 本地通知适用于在特定时间发出的通知,如一些 Todo 和闹钟类的应用,在每周、每月固定时间提醒用户回到应用查看任务。

推送人群(Audience)

  1. 广播(所有人)
  2. 注册ID(RegistrationID)
  3. 别名(alias)
  4. 标签(tag,分组)
  5. 用户分群(Segment)

注册ID(RegistrationID)

RegistrationID 就是这台设备(以及当前这个 App),被推送服务器分配的唯一 ID。不同的设备、不同的 App 这个 ID 肯定不同的。

SDK 在第一次启动时会去服务器端进行注册并识别,服务器端会分配一个 RegistrationID。SDK 会把这个 ID 通过广播(或通知)的方式发给 App。SDK 也提供了获取 RegistrationID 的接口。

如果一个 App 在这台设备上之前安装过,然后被卸载掉。重新安装时,其获取到的 RegistrationID 有一定的可能性不变。这取决于平台以及条件。

  • Android 上 JPush 会综合利用多个条件来判断设备是否相同,从而 RegistrationID 不变的可能性很大。
  • iOS 老版本上,因为 device token 重新安装 App 时也不会变,从而 RegistrationID 也一般不会变。
  • iOS8 以后重新安装 App 会导致 device token 变更,iOS 上如果不启用 IDFA 则没有其他可用于识别设备的手段,从而 RegistrationID 一般会变化。或者说,服务器端无法识别重新安装。所以如果你的业务有需要,建议启用 IDFA。

使用 RegistrationID 推送的关键于,App 开发者需要在开发 App 时,获取到这个 RegistrationID,保存到 App 业务服务器上去,并且与自己的用户标识对应起来。

建议 App 开发者尽可能做这个保存动作。因为这是最精确地定位到设备的。

别名(alias)

别名可以理解为基于 RegistrationID,设置一个更容易理解的『别名』,比如直接设置为当前登录用户的 username。

一个设备(在一个 App 里)只能设置一个别名。

别名的本质是,把 App 用户体系里的用户ID与 RegistrationID 的对应关系,保存到推送服务器上,而不是保存到 App 业务服务器上去。(使用 RegistrationID 就是把对应关系保存到 App 业务服务器上去。)

设置了别名后,推送时服务器端指定别名即可。推送服务器端来把别名转化到 RegistrationID找到设备。

别名可以在客户端设置,服务器端也提供了 REST API 进行设置。但是,在一个 App 的生命周期中,强烈建议不要既在客户端又在服务器端进行设置,否则会导致混乱。

标签(tag)

又或者称为分组推送。对于大量的设置了同一个标签的终端,可以一次推送到到达。一个应用里一个标签绑定到的设备数没有限制。

一个设备(在一个 App里)可以设置多个标签。

标签与别名类似,其对应关系也是保存在推送服务器侧的。

与别名类似,标签也是可以在客户端设置,服务器端也开放了 REST API 进行设置。同样,也是强烈建议,不要既在客户端设置标签,又在服务器端设置标签,以免造成混乱。

用户分群(Segment)

这是相对高级的使用方式了,开发者可以根据一些已知的条件,任意组合,创建一个 SegmentID。然后基于这个 SegmentID 进行推送。

上面说到的可以用于用户分群的条件有:tags,App 版本,SDK 版本,平台版本,用户注册时间,用户活跃时间,用户所在城市等。

广播(所有人)

技术上广播很好理解,就是推送给所有安装的 App 的设备终端。

极光推送对广播有一个特殊的选项:延迟推送。这是个很有特色的功能,让推送在一定时长内平均分配,而不是在太短时间内完成,以免对 App 业务服务器造成太大的压力。

根据业务场景选择推送人群

以上以极光推送为例介绍了支持的推送人群类别。但是,任何技术都有一个使用场景的问题。开发者需要想清楚自己的使用场景,来选择适当的类别。

单用户推送

RegistrationID 与别名是设计用来单用户推送的。

如果别名只是在一个设备上被设置,则其效果与 RegistrationID 是类似的。

不同的是,一个别名是可以被设置到多设备上的。一个常见的场景是,把 App 的用户帐号 username 作为别名。一个 App用户帐号可以在多设备上登录(大多数这样),就可以在多设备上绑定为别名。这样推送给这个别名,多设备上都收到。

由于别名的绑定关系保存在推送服务器上,App 业务上要做变更就不够灵活。所以,别名更适合于简单的使用场景,也是适合「懒」的开发者。而 App 想要有灵活性,建议使用 RegistrationID 的方式。

别名在使用时,有可能被误使用为 tag,即大量的设备上都设置同一个别名,其实就是 tag 的使用方式。极光推送发现了不少 App 这样子用。

用户分群与标签

标签是个很灵活的分组方法,可以被用于业务强相关的各种场景。主要的种类有:订阅,用户属性。

订阅类,比如彩票 App 用于用户订阅不同彩票类型的最新开奖信息,阅读类 App 用于让用户订阅多个频道的最新资讯等。

用 tag 来标注用户的属性,比如性别、年龄段、喜好、关注等,也是个很常见的作法,这样推送时就可以基于这些属性来做。这也是精细化推送的基础。

事实上,很多标签被开发者定义为:App 版本,用户城市,使用语言等等。现在很多这类的 tags 可以不要了,只需要直接使用用户分群功能就可以了。

二.代码

1.导入依赖

  1. <!-- jpush -->
  2. <dependency>
  3. <groupId>cn.jpush.api</groupId>
  4. <artifactId>jpush-client</artifactId>
  5. <version>3.3.9</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>cn.jpush.api</groupId>
  9. <artifactId>jiguang-common</artifactId>
  10. <version>1.0.3</version>
  11. </dependency>

2.极光推送工具类

1.一类

  1. package com.zh.erp.framework.util.jpush;
  2. import cn.jiguang.common.ClientConfig;
  3. import cn.jiguang.common.ServiceHelper;
  4. import cn.jiguang.common.connection.NativeHttpClient;
  5. import cn.jiguang.common.connection.NettyHttpClient;
  6. import cn.jiguang.common.resp.APIConnectionException;
  7. import cn.jiguang.common.resp.APIRequestException;
  8. import cn.jiguang.common.resp.ResponseWrapper;
  9. import cn.jpush.api.JPushClient;
  10. import cn.jpush.api.push.CIDResult;
  11. import cn.jpush.api.push.GroupPushClient;
  12. import cn.jpush.api.push.PushResult;
  13. import cn.jpush.api.push.model.*;
  14. import cn.jpush.api.push.model.audience.Audience;
  15. import cn.jpush.api.push.model.audience.AudienceTarget;
  16. import cn.jpush.api.push.model.notification.*;
  17. import com.google.gson.Gson;
  18. import com.google.gson.GsonBuilder;
  19. import com.google.gson.JsonObject;
  20. import com.google.gson.JsonPrimitive;
  21. import io.netty.handler.codec.http.HttpMethod;
  22. import org.slf4j.Logger;
  23. import org.slf4j.LoggerFactory;
  24. import java.net.URI;
  25. import java.net.URISyntaxException;
  26. import java.util.*;
  27. public class PushExample {
  28. protected static final Logger LOG = LoggerFactory.getLogger(PushExample.class);
  29. // demo App defined in resources/jpush-api.conf
  30. protected static final String APP_KEY1 = "274e2f473f13f6fa679368ae";
  31. protected static final String APP_KEY = "ebd355e590e6f7f93ba51477";
  32. protected static final String MASTER_SECRET1 = "896bb372344468fc0e3e47d4";
  33. protected static final String MASTER_SECRET = "2604f3b0706d46bd47ba919b";
  34. protected static final String GROUP_PUSH_KEY = "caff9bd51218a2def8d1a350";
  35. protected static final String GROUP_MASTER_SECRET = "06edba1d32ca66d9a54fd787";
  36. public static final String TITLE = "Test from API example";
  37. public static final String ALERT = "Test from API Example - alert";
  38. public static final String MSG_CONTENT = "Test from API Example - msgContent";
  39. public static final String REGISTRATION_ID = "0900e8d85ef";
  40. public static final String TAG = "tag_api";
  41. public static long sendCount = 0;
  42. private static long sendTotalTime = 0;
  43. public static void main(String[] args) {
  44. // 回调参数可参考下面方法
  45. // testSendPushWithCustom(); //
  46. // testSendPushWithCustomField(); //
  47. // testBatchSend();
  48. // testSendPushWithCustomConfig(); //
  49. asynSendMessageWithCallback("user_1648_1062","您有一个新任务等待处理!","您有一个新任务等待处理!",
  50. "上海市浦东新区祝桥镇大沙路东海集贸市场","上海市浦东新区祝桥镇大沙路东海集贸市场","");
  51. //pushAline("user_1648_1062","您有一个新任务等待处理!","上海市浦东新区祝桥镇大沙路东海集贸市场");
  52. // testSendIosAlert();
  53. // testSendPush();
  54. // testGetCidList();
  55. // testSendPushes();
  56. // testSendPush_fromJSON(); //
  57. // testSendPushWithCallback();
  58. // testSendPushWithCid();
  59. }
  60. // 使用 NettyHttpClient 异步接口发送请求
  61. public static void testSendPushWithCallback() {
  62. ClientConfig clientConfig = ClientConfig.getInstance();
  63. String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME);
  64. final NettyHttpClient client = new NettyHttpClient(ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET),
  65. null, clientConfig);
  66. try {
  67. URI uri = new URI(host + clientConfig.get(ClientConfig.PUSH_PATH));
  68. PushPayload payload = buildPushObject_all_alias_alert();
  69. client.sendRequest(HttpMethod.POST, payload.toString(), uri, new NettyHttpClient.BaseCallback() {
  70. @Override
  71. public void onSucceed(ResponseWrapper responseWrapper) {
  72. LOG.info("Got result: " + responseWrapper.responseContent);
  73. }
  74. });
  75. } catch (URISyntaxException e) {
  76. e.printStackTrace();
  77. }
  78. }
  79. public static void testSendPush() {
  80. ClientConfig clientConfig = ClientConfig.getInstance();
  81. final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
  82. // String authCode = ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET);
  83. // Here you can use NativeHttpClient or NettyHttpClient or ApacheHttpClient.
  84. // Call setHttpClient to set httpClient,
  85. // If you don't invoke this method, default httpClient will use NativeHttpClient.
  86. // ApacheHttpClient httpClient = new ApacheHttpClient(authCode, null, clientConfig);
  87. // NettyHttpClient httpClient =new NettyHttpClient(authCode, null, clientConfig);
  88. // jpushClient.getPushClient().setHttpClient(httpClient);
  89. final PushPayload payload = buildPushObject_android_and_ios();
  90. // // For push, all you need do is to build PushPayload object.
  91. // PushPayload payload = buildPushObject_all_alias_alert();
  92. try {
  93. PushResult result = jpushClient.sendPush(payload);
  94. LOG.info("Got result - " + result);
  95. System.out.println(result);
  96. // 如果使用 NettyHttpClient,需要手动调用 close 方法退出进程
  97. // If uses NettyHttpClient, call close when finished sending request, otherwise process will not exit.
  98. // jpushClient.close();
  99. } catch (APIConnectionException e) {
  100. LOG.error("Connection error. Should retry later. ", e);
  101. LOG.error("Sendno: " + payload.getSendno());
  102. } catch (APIRequestException e) {
  103. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  104. LOG.info("HTTP Status: " + e.getStatus());
  105. LOG.info("Error Code: " + e.getErrorCode());
  106. LOG.info("Error Message: " + e.getErrorMessage());
  107. LOG.info("Msg ID: " + e.getMsgId());
  108. LOG.error("Sendno: " + payload.getSendno());
  109. }
  110. }
  111. public static void testSendPushWithEncrypt() {
  112. ClientConfig clientConfig = ClientConfig.getInstance();
  113. clientConfig.setEncryptType(EncryptKeys.ENCRYPT_SMS2_TYPE);
  114. final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
  115. // String authCode = ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET);
  116. // Here you can use NativeHttpClient or NettyHttpClient or ApacheHttpClient.
  117. // Call setHttpClient to set httpClient,
  118. // If you don't invoke this method, default httpClient will use NativeHttpClient.
  119. // ApacheHttpClient httpClient = new ApacheHttpClient(authCode, null, clientConfig);
  120. // NettyHttpClient httpClient =new NettyHttpClient(authCode, null, clientConfig);
  121. // jpushClient.getPushClient().setHttpClient(httpClient);
  122. final PushPayload payload = buildPushObject_android_and_ios();
  123. // // For push, all you need do is to build PushPayload object.
  124. // PushPayload payload = buildPushObject_all_alias_alert();
  125. try {
  126. PushResult result = jpushClient.sendPush(payload);
  127. LOG.info("Got result - " + result);
  128. System.out.println(result);
  129. // 如果使用 NettyHttpClient,需要手动调用 close 方法退出进程
  130. // If uses NettyHttpClient, call close when finished sending request, otherwise process will not exit.
  131. // jpushClient.close();
  132. } catch (APIConnectionException e) {
  133. LOG.error("Connection error. Should retry later. ", e);
  134. LOG.error("Sendno: " + payload.getSendno());
  135. } catch (APIRequestException e) {
  136. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  137. LOG.info("HTTP Status: " + e.getStatus());
  138. LOG.info("Error Code: " + e.getErrorCode());
  139. LOG.info("Error Message: " + e.getErrorMessage());
  140. LOG.info("Msg ID: " + e.getMsgId());
  141. LOG.error("Sendno: " + payload.getSendno());
  142. }
  143. }
  144. //use String to build PushPayload instance
  145. public static void testSendPush_fromJSON() {
  146. ClientConfig clientConfig = ClientConfig.getInstance();
  147. JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
  148. Gson gson = new GsonBuilder()
  149. .registerTypeAdapter(PlatformNotification.class, new InterfaceAdapter<PlatformNotification>())
  150. .create();
  151. // Since the type of DeviceType is enum, thus the value should be uppercase, same with the AudienceType.
  152. 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}}";
  153. PushPayload payload = gson.fromJson(payloadString, PushPayload.class);
  154. try {
  155. PushResult result = jpushClient.sendPush(payloadString);
  156. LOG.info("Got result - " + result);
  157. } catch (APIConnectionException e) {
  158. LOG.error("Connection error. Should retry later. ", e);
  159. // LOG.error("Sendno: " + payload.getSendno());
  160. } catch (APIRequestException e) {
  161. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  162. LOG.info("HTTP Status: " + e.getStatus());
  163. LOG.info("Error Code: " + e.getErrorCode());
  164. LOG.info("Error Message: " + e.getErrorMessage());
  165. LOG.info("Msg ID: " + e.getMsgId());
  166. //LOG.error("Sendno: " + payload.getSendno());
  167. }
  168. }
  169. /**
  170. * 测试多线程发送 2000 条推送耗时
  171. */
  172. public static void testSendPushes() {
  173. ClientConfig clientConfig = ClientConfig.getInstance();
  174. final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
  175. String authCode = ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET);
  176. // Here you can use NativeHttpClient or NettyHttpClient or ApacheHttpClient.
  177. NativeHttpClient httpClient = new NativeHttpClient(authCode, null, clientConfig);
  178. // Call setHttpClient to set httpClient,
  179. // If you don't invoke this method, default httpClient will use NativeHttpClient.
  180. // ApacheHttpClient httpClient = new ApacheHttpClient(authCode, null, clientConfig);
  181. jpushClient.getPushClient().setHttpClient(httpClient);
  182. final PushPayload payload = buildPushObject_ios_tagAnd_alertWithExtrasAndMessage();
  183. for (int i = 0; i < 10; i++) {
  184. Thread thread = new Thread() {
  185. public void run() {
  186. for (int j = 0; j < 200; j++) {
  187. long start = System.currentTimeMillis();
  188. try {
  189. PushResult result = jpushClient.sendPush(payload);
  190. LOG.info("Got result - " + result);
  191. } catch (APIConnectionException e) {
  192. LOG.error("Connection error. Should retry later. ", e);
  193. LOG.error("Sendno: " + payload.getSendno());
  194. } catch (APIRequestException e) {
  195. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  196. LOG.info("HTTP Status: " + e.getStatus());
  197. LOG.info("Error Code: " + e.getErrorCode());
  198. LOG.info("Error Message: " + e.getErrorMessage());
  199. LOG.info("Msg ID: " + e.getMsgId());
  200. LOG.error("Sendno: " + payload.getSendno());
  201. }
  202. System.out.println("耗时" + (System.currentTimeMillis() - start) + "毫秒 sendCount:" + (++sendCount));
  203. }
  204. }
  205. };
  206. thread.start();
  207. }
  208. }
  209. public void testSendGroupPush() {
  210. GroupPushClient groupPushClient = new GroupPushClient(GROUP_MASTER_SECRET, GROUP_PUSH_KEY);
  211. final PushPayload payload = buildPushObject_android_and_ios();
  212. try {
  213. Map<String, PushResult> result = groupPushClient.sendGroupPush(payload);
  214. for (Map.Entry<String, PushResult> entry : result.entrySet()) {
  215. PushResult pushResult = entry.getValue();
  216. PushResult.Error error = pushResult.error;
  217. if (error != null) {
  218. LOG.info("AppKey: " + entry.getKey() + " error code : " + error.getCode() + " error message: " + error.getMessage());
  219. } else {
  220. LOG.info("AppKey: " + entry.getKey() + " sendno: " + pushResult.sendno + " msg_id:" + pushResult.msg_id);
  221. }
  222. }
  223. } catch (APIConnectionException e) {
  224. LOG.error("Connection error. Should retry later. ", e);
  225. LOG.error("Sendno: " + payload.getSendno());
  226. } catch (APIRequestException e) {
  227. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  228. LOG.info("HTTP Status: " + e.getStatus());
  229. LOG.info("Error Code: " + e.getErrorCode());
  230. LOG.info("Error Message: " + e.getErrorMessage());
  231. LOG.info("Msg ID: " + e.getMsgId());
  232. LOG.error("Sendno: " + payload.getSendno());
  233. }
  234. }
  235. public static PushPayload buildPushObject_all_all_alert() {
  236. return PushPayload.alertAll(ALERT);
  237. }
  238. public static PushPayload buildPushObject_all_alias_alert() {
  239. return PushPayload.newBuilder()
  240. .setPlatform(Platform.all())
  241. .setAudience(Audience.alias("alias1"))
  242. .setNotification(Notification.alert(ALERT))
  243. .build();
  244. }
  245. public static PushPayload buildPushObject_android_tag_alertWithTitle() {
  246. return PushPayload.newBuilder()
  247. .setPlatform(Platform.android())
  248. .setAudience(Audience.tag("tag1"))
  249. .setNotification(Notification.android(ALERT, TITLE, null))
  250. .build();
  251. }
  252. public static PushPayload buildPushObject_android_and_ios() {
  253. Map<String, String> extras = new HashMap<String, String>();
  254. extras.put("test", "https://community.jiguang.cn/push");
  255. return PushPayload.newBuilder()
  256. .setPlatform(Platform.android_ios())
  257. .setAudience(Audience.all())
  258. .setNotification(Notification.newBuilder()
  259. .setAlert("alert content")
  260. .addPlatformNotification(AndroidNotification.newBuilder()
  261. .setTitle("Android Title")
  262. .addExtras(extras).build())
  263. .addPlatformNotification(IosNotification.newBuilder()
  264. .incrBadge(1)
  265. .addExtra("extra_key", "extra_value").build())
  266. .build())
  267. .build();
  268. }
  269. public static void buildPushObject_with_extra() {
  270. JsonObject jsonExtra = new JsonObject();
  271. jsonExtra.addProperty("extra1", 1);
  272. jsonExtra.addProperty("extra2", false);
  273. Map<String, String> extras = new HashMap<String, String>();
  274. extras.put("extra_1", "val1");
  275. extras.put("extra_2", "val2");
  276. PushPayload payload = PushPayload.newBuilder()
  277. .setPlatform(Platform.android_ios())
  278. .setAudience(Audience.tag("tag1"))
  279. .setNotification(Notification.newBuilder()
  280. .setAlert("alert content")
  281. .addPlatformNotification(AndroidNotification.newBuilder()
  282. .setTitle("Android Title")
  283. .addExtras(extras)
  284. .addExtra("booleanExtra", false)
  285. .addExtra("numberExtra", 1)
  286. .addExtra("jsonExtra", jsonExtra)
  287. .build())
  288. .addPlatformNotification(IosNotification.newBuilder()
  289. .incrBadge(1)
  290. .addExtra("extra_key", "extra_value").build())
  291. .build())
  292. .build();
  293. System.out.println(payload.toJSON());
  294. }
  295. public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage() {
  296. JsonObject sound = new JsonObject();
  297. sound.add("critical", new JsonPrimitive(1));
  298. sound.add("name", new JsonPrimitive("default"));
  299. sound.add("volume", new JsonPrimitive(0.2));
  300. return PushPayload.newBuilder()
  301. .setPlatform(Platform.ios())
  302. .setAudience(Audience.tag_and("tag1", "tag_all"))
  303. .setNotification(Notification.newBuilder()
  304. .addPlatformNotification(IosNotification.newBuilder()
  305. .setAlert(ALERT)
  306. .setBadge(5)
  307. .setMutableContent(false)
  308. // .setSound("happy")
  309. .setSound(sound)
  310. .addExtra("from", "JPush")
  311. .build())
  312. .build())
  313. .setMessage(Message.content(MSG_CONTENT))
  314. .setOptions(Options.newBuilder()
  315. .setApnsProduction(true)
  316. .build())
  317. .build();
  318. }
  319. public static PushPayload buildPushObject_android_newly_support() {
  320. JsonObject inbox = new JsonObject();
  321. inbox.add("line1", new JsonPrimitive("line1 string"));
  322. inbox.add("line2", new JsonPrimitive("line2 string"));
  323. inbox.add("contentTitle", new JsonPrimitive("title string"));
  324. inbox.add("summaryText", new JsonPrimitive("+3 more"));
  325. JsonObject intent = new JsonObject();
  326. intent.add("url", new JsonPrimitive("intent:#Intent;component=com.jiguang.push/com.example.jpushdemo.SettingActivity;end"));
  327. Notification notification = Notification.newBuilder()
  328. .addPlatformNotification(AndroidNotification.newBuilder()
  329. .setAlert(ALERT)
  330. .setBigPicPath("path to big picture")
  331. .setBigText("long text")
  332. .setBuilderId(1)
  333. .setCategory("CATEGORY_SOCIAL")
  334. .setInbox(inbox)
  335. .setStyle(1)
  336. .setTitle("Alert test")
  337. .setPriority(1)
  338. .setLargeIcon("http://www.jiguang.cn/largeIcon.jpg")
  339. .setIntent(intent)
  340. .build())
  341. .build();
  342. return PushPayload.newBuilder()
  343. .setPlatform(Platform.all())
  344. .setAudience(Audience.all())
  345. .setNotification(notification)
  346. .setOptions(Options.newBuilder()
  347. .setApnsProduction(true)
  348. .setSendno(ServiceHelper.generateSendno())
  349. .build())
  350. .build();
  351. }
  352. public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {
  353. return PushPayload.newBuilder()
  354. .setPlatform(Platform.android_ios())
  355. .setAudience(Audience.newBuilder()
  356. .addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))
  357. .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
  358. .build())
  359. .setMessage(Message.newBuilder()
  360. .setMsgContent(MSG_CONTENT)
  361. .addExtra("from", "JPush")
  362. .build())
  363. .build();
  364. }
  365. public static PushPayload buildPushObject_all_tag_not() {
  366. return PushPayload.newBuilder()
  367. .setPlatform(Platform.all())
  368. .setAudience(Audience.tag_not("abc", "123"))
  369. .setNotification(Notification.alert(ALERT))
  370. .build();
  371. }
  372. public static PushPayload buildPushObject_android_cid() {
  373. Collection<String> list = new LinkedList<String>();
  374. list.add("1507bfd3f79558957de");
  375. list.add("1507bfd3f79554957de");
  376. list.add("1507bfd3f79555957de");
  377. list.add("1507bfd3f79556957de");
  378. list.add("1507ffd3f79545957de");
  379. list.add("1507ffd3f79457957de");
  380. list.add("1507ffd3f79456757de");
  381. return PushPayload.newBuilder()
  382. .setPlatform(Platform.android())
  383. // .setAudience(Audience.registrationId("1507bfd3f79558957de"))
  384. .setAudience(Audience.registrationId(list))
  385. .setNotification(Notification.alert(ALERT))
  386. .setCid("cid")
  387. .build();
  388. }
  389. public static void testSendPushWithCustomConfig() {
  390. ClientConfig config = ClientConfig.getInstance();
  391. // Setup the custom hostname
  392. config.setPushHostName("https://api.jpush.cn");
  393. JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, config);
  394. // For push, all you need do is to build PushPayload object.
  395. PushPayload payload = buildPushObject_all_all_alert();
  396. try {
  397. PushResult result = jpushClient.sendPush(payload);
  398. LOG.info("Got result - " + result);
  399. } catch (APIConnectionException e) {
  400. LOG.error("Connection error. Should retry later. ", e);
  401. } catch (APIRequestException e) {
  402. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  403. LOG.info("HTTP Status: " + e.getStatus());
  404. LOG.info("Error Code: " + e.getErrorCode());
  405. LOG.info("Error Message: " + e.getErrorMessage());
  406. LOG.info("Msg ID: " + e.getMsgId());
  407. }
  408. }
  409. public static void testSendIosAlert() {
  410. JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY);
  411. IosAlert alert = IosAlert.newBuilder()
  412. .setTitleAndBody("test alert", "subtitle", "test ios alert json")
  413. .setActionLocKey("PLAY")
  414. .build();
  415. try {
  416. PushResult result = jpushClient.sendIosNotificationWithAlias(alert, new HashMap<String, String>(), "alias1");
  417. LOG.info("Got result - " + result);
  418. } catch (APIConnectionException e) {
  419. LOG.error("Connection error. Should retry later. ", e);
  420. } catch (APIRequestException e) {
  421. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  422. LOG.info("HTTP Status: " + e.getStatus());
  423. LOG.info("Error Code: " + e.getErrorCode());
  424. LOG.info("Error Message: " + e.getErrorMessage());
  425. }
  426. }
  427. public static void testSendWithSMS() {
  428. JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY);
  429. try {
  430. // SMS sms = SMS.content(1, 10);
  431. SMS sms = SMS.newBuilder()
  432. .setDelayTime(1000)
  433. .setTempID(2000)
  434. .addPara("Test", 1)
  435. .build();
  436. PushResult result = jpushClient.sendAndroidMessageWithAlias("Test SMS", "test sms", sms, "alias1");
  437. LOG.info("Got result - " + result);
  438. } catch (APIConnectionException e) {
  439. LOG.error("Connection error. Should retry later. ", e);
  440. } catch (APIRequestException e) {
  441. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  442. LOG.info("HTTP Status: " + e.getStatus());
  443. LOG.info("Error Code: " + e.getErrorCode());
  444. LOG.info("Error Message: " + e.getErrorMessage());
  445. }
  446. }
  447. public static void testGetCidList() {
  448. JPushClient jPushClient = new JPushClient(MASTER_SECRET, APP_KEY);
  449. try {
  450. CIDResult result = jPushClient.getCidList(3, "push");
  451. LOG.info("Got result - " + result);
  452. } catch (APIConnectionException e) {
  453. LOG.error("Connection error. Should retry later. ", e);
  454. } catch (APIRequestException e) {
  455. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  456. LOG.info("HTTP Status: " + e.getStatus());
  457. LOG.info("Error Code: " + e.getErrorCode());
  458. LOG.info("Error Message: " + e.getErrorMessage());
  459. }
  460. }
  461. public static void testSendPushWithCid() {
  462. JPushClient jPushClient = new JPushClient(MASTER_SECRET, APP_KEY);
  463. PushPayload pushPayload = buildPushObject_android_cid();
  464. try {
  465. PushResult result = jPushClient.sendPush(pushPayload);
  466. LOG.info("Got result - " + result);
  467. } catch (APIConnectionException e) {
  468. LOG.error("Connection error. Should retry later. ", e);
  469. } catch (APIRequestException e) {
  470. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  471. LOG.info("HTTP Status: " + e.getStatus());
  472. LOG.info("Error Code: " + e.getErrorCode());
  473. LOG.info("Error Message: " + e.getErrorMessage());
  474. }
  475. }
  476. /**
  477. * 批量单推接口
  478. * https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/#vip
  479. */
  480. public static void testBatchSend() {
  481. JPushClient jPushClient = new JPushClient(MASTER_SECRET, APP_KEY);
  482. try {
  483. {
  484. List<PushPayload> pushPayloadList = new ArrayList<>();
  485. PushPayload.Builder builder1 = PushPayload.newBuilder();
  486. builder1.setMessage(Message.content("content1 by alias"))
  487. .setNotification(Notification.alert(ALERT))
  488. .setPlatform(Platform.all())
  489. .setAudience(Audience.all())
  490. .setOptions(Options.sendno())
  491. .setTarget("1507ffd3f79456757de");
  492. pushPayloadList.add(builder1.build());
  493. PushPayload.Builder builder2 = PushPayload.newBuilder();
  494. builder2.setMessage(Message.content("content2 by alias"))
  495. .setNotification(Notification.alert(ALERT))
  496. .setPlatform(Platform.android())
  497. .setAudience(Audience.all())
  498. .setOptions(Options.sendno())
  499. .setTarget("1507ffd3f79456757de");
  500. pushPayloadList.add(builder2.build());
  501. BatchPushResult result = jPushClient.batchSendPushByAlias(pushPayloadList);
  502. LOG.info("batchSendPushByAlias param: {}, result: {}", pushPayloadList, new Gson().toJson(result.getBatchPushResult()));
  503. }
  504. {
  505. List<PushPayload> pushPayloadList = new ArrayList<>();
  506. PushPayload.Builder builder1 = PushPayload.newBuilder();
  507. builder1.setMessage(Message.content("content1 by regId"))
  508. .setNotification(Notification.alert(ALERT))
  509. .setPlatform(Platform.android())
  510. .setAudience(Audience.all())
  511. .setOptions(Options.sendno())
  512. .setTarget("1507ffd3f79456757de");
  513. pushPayloadList.add(builder1.build());
  514. PushPayload.Builder builder2 = PushPayload.newBuilder();
  515. builder2.setMessage(Message.content("content2 by regId"))
  516. .setNotification(Notification.alert(ALERT))
  517. .setAudience(Audience.all())
  518. .setPlatform(Platform.ios())
  519. .setOptions(Options.sendno())
  520. .setTarget("1507ffd3f79456757de");
  521. pushPayloadList.add(builder2.build());
  522. BatchPushResult result = jPushClient.batchSendPushByRegId(pushPayloadList);
  523. LOG.info("batchSendPushByRegId param: {}, result: {}", pushPayloadList, new Gson().toJson(result.getBatchPushResult()));
  524. }
  525. } catch (APIConnectionException e) {
  526. LOG.error("Connection error. Should retry later. ", e);
  527. } catch (APIRequestException e) {
  528. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  529. LOG.info("HTTP Status: " + e.getStatus());
  530. LOG.info("Error Code: " + e.getErrorCode());
  531. LOG.info("Error Message: " + e.getErrorMessage());
  532. }
  533. }
  534. /**
  535. * 自定义发送参数名称, 华为客户可参考该方法
  536. */
  537. public static void testSendPushWithCustomField() {
  538. ClientConfig config = ClientConfig.getInstance();
  539. // Setup the custom hostname
  540. config.setPushHostName("https://api.jpush.cn");
  541. JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, config);
  542. Notification notification = Notification.newBuilder()
  543. .addPlatformNotification(AndroidNotification.newBuilder()
  544. .setAlert(ALERT)
  545. .setTitle("Alert test")
  546. .setLargeIcon("http://www.jiguang.cn/largeIcon.jpg")
  547. .addCustom("uri_activity", "uri_activity")
  548. .addCustom("uri_flag", "uri_flag")
  549. .addCustom("uri_action", "uri_action")
  550. .build())
  551. .build();
  552. PushPayload.Builder payloadBuilder = new PushPayload.Builder()
  553. .setPlatform(Platform.all())
  554. .setAudience(Audience.all())
  555. .setNotification(notification);
  556. try {
  557. PushResult result = jpushClient.sendPush(payloadBuilder.build());
  558. LOG.info("Got result - " + result);
  559. } catch (APIConnectionException e) {
  560. LOG.error("Connection error. Should retry later. ", e);
  561. } catch (APIRequestException e) {
  562. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  563. LOG.info("HTTP Status: " + e.getStatus());
  564. LOG.info("Error Code: " + e.getErrorCode());
  565. LOG.info("Error Message: " + e.getErrorMessage());
  566. LOG.info("Msg ID: " + e.getMsgId());
  567. }
  568. }
  569. /**
  570. * 回调参数示例
  571. */
  572. public static void testSendPushWithCustom() {
  573. ClientConfig config = ClientConfig.getInstance();
  574. // Setup the custom hostname
  575. config.setPushHostName("https://api.jpush.cn");
  576. JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, config);
  577. Notification notification = Notification.newBuilder()
  578. .addPlatformNotification(AndroidNotification.newBuilder()
  579. .setAlert(ALERT)
  580. .setTitle("Alert test")
  581. .build())
  582. .build();
  583. JsonObject callback = new JsonObject();
  584. callback.addProperty("url", "https://www.jiguagn.cn/callback");
  585. JsonObject params = new JsonObject();
  586. params.addProperty("name", "joe");
  587. params.addProperty("age", 26);
  588. callback.add("params", params);
  589. callback.addProperty("type", 3);
  590. PushPayload.Builder payloadBuilder = new PushPayload.Builder()
  591. .setPlatform(Platform.all())
  592. .setAudience(Audience.all())
  593. .setNotification(notification)
  594. .addCustom("callback", callback);
  595. try {
  596. PushResult result = jpushClient.sendPush(payloadBuilder.build());
  597. LOG.info("Got result - " + result);
  598. } catch (APIConnectionException e) {
  599. LOG.error("Connection error. Should retry later. ", e);
  600. } catch (APIRequestException e) {
  601. LOG.error("Error response from JPush server. Should review and fix it. ", e);
  602. LOG.info("HTTP Status: " + e.getStatus());
  603. LOG.info("Error Code: " + e.getErrorCode());
  604. LOG.info("Error Message: " + e.getErrorMessage());
  605. LOG.info("Msg ID: " + e.getMsgId());
  606. }
  607. }
  608. public static void asynSendMessageWithCallback(String alias, String notification_title, String msg_title, String msg_content, String extrasparam, String content_type) {
  609. ClientConfig clientConfig = ClientConfig.getInstance();
  610. String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME);
  611. System.out.println(APP_KEY+"***"+MASTER_SECRET+";"+APP_KEY1+"***"+MASTER_SECRET1);
  612. final NettyHttpClient client = new NettyHttpClient(ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET),
  613. null, clientConfig);
  614. final NettyHttpClient client1 = new NettyHttpClient(ServiceHelper.getBasicAuthorization(APP_KEY1, MASTER_SECRET1),
  615. null, clientConfig);
  616. try {
  617. URI uri = new URI(host + clientConfig.get(ClientConfig.PUSH_PATH));
  618. PushPayload payload = buildPushObject_android_alias_alertWithTitle(alias, notification_title, msg_title, msg_content, extrasparam, content_type);
  619. System.out.println("payload="+payload+";uri="+uri);
  620. client.sendRequest(HttpMethod.POST, payload.toString(), uri, new NettyHttpClient.BaseCallback() {
  621. @Override
  622. public void onSucceed(ResponseWrapper responseWrapper) {
  623. LOG.info("Got result: " + responseWrapper.responseContent);
  624. System.out.println("Got result: " + responseWrapper.responseContent);
  625. }
  626. });
  627. client1.sendRequest(HttpMethod.POST, payload.toString(), uri, new NettyHttpClient.BaseCallback() {
  628. @Override
  629. public void onSucceed(ResponseWrapper responseWrapper) {
  630. LOG.info("Got result1: " + responseWrapper.responseContent);
  631. System.out.println("Got result1: " + responseWrapper.responseContent);
  632. }
  633. });
  634. } catch (URISyntaxException e) {
  635. e.printStackTrace();
  636. }
  637. }
  638. private static PushPayload buildPushObject_android_alias_alertWithTitle(String alias, String notification_title, String msg_title, String msg_content, String extrasparam, String content_type) {
  639. return PushPayload.newBuilder()
  640. //指定要推送的平台,all代表当前应用配置了的所有平台,也可以传android等具体平台
  641. .setPlatform(Platform.android())
  642. //指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
  643. .setAudience(Audience.alias(alias))
  644. //.setAudience(Audience.all())
  645. //jpush的通知,android的由jpush直接下发,iOS的由apns服务器下发,Winphone的由mpns下发
  646. .setNotification(Notification.newBuilder()
  647. //指定当前推送的android通知
  648. .addPlatformNotification(AndroidNotification.newBuilder()
  649. .setAlert(msg_content)
  650. .setTitle(notification_title)
  651. //此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
  652. .addExtra("data", extrasparam)
  653. .build())
  654. .build()
  655. )
  656. //Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
  657. // sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
  658. // [通知与自定义消息有什么区别?]了解通知和自定义消息的区别
  659. .setMessage(Message.newBuilder()
  660. .setMsgContent(msg_content)
  661. .setTitle(msg_title)
  662. .setContentType(content_type)
  663. .addExtra("data", extrasparam)
  664. .build())
  665. .setOptions(Options.newBuilder()
  666. //此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
  667. .setApnsProduction(true)
  668. //此字段是给开发者自己给推送编号,方便推送者分辨推送记录
  669. .setSendno(1)
  670. //此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天,单位为秒
  671. .setTimeToLive(86400)
  672. .build())
  673. .build();
  674. }
  675. public static void asynSendMessageWithCallbackAll(String tag, String notification_title, String msg_title, String msg_content, String extrasparam, String content_type) {
  676. ClientConfig clientConfig = ClientConfig.getInstance();
  677. String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME);
  678. final NettyHttpClient client = new NettyHttpClient(ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET),
  679. null, clientConfig);
  680. try {
  681. URI uri = new URI(host + clientConfig.get(ClientConfig.PUSH_PATH));
  682. PushPayload payload = buildPushObject_android_alias_alertWithTitleAll(tag, notification_title, msg_title, msg_content, extrasparam, content_type);
  683. client.sendRequest(HttpMethod.POST, payload.toString(), uri, new NettyHttpClient.BaseCallback() {
  684. @Override
  685. public void onSucceed(ResponseWrapper responseWrapper) {
  686. LOG.info("Got result: " + responseWrapper.responseContent);
  687. }
  688. });
  689. } catch (URISyntaxException e) {
  690. e.printStackTrace();
  691. }
  692. }
  693. private static PushPayload buildPushObject_android_alias_alertWithTitleAll(String tag, String notification_title, String msg_title, String msg_content, String extrasparam, String content_type) {
  694. return PushPayload.newBuilder()
  695. //指定要推送的平台,all代表当前应用配置了的所有平台,也可以传android等具体平台
  696. .setPlatform(Platform.android())
  697. //指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
  698. .setAudience(Audience.tag(tag))
  699. //jpush的通知,android的由jpush直接下发,iOS的由apns服务器下发,Winphone的由mpns下发
  700. .setNotification(Notification.newBuilder()
  701. //指定当前推送的android通知
  702. .addPlatformNotification(AndroidNotification.newBuilder()
  703. .setAlert(msg_content)
  704. .setTitle(notification_title)
  705. //此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
  706. .addExtra("data", extrasparam)
  707. .build())
  708. .build()
  709. )
  710. //Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
  711. // sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
  712. // [通知与自定义消息有什么区别?]了解通知和自定义消息的区别
  713. .setMessage(Message.newBuilder()
  714. .setMsgContent(msg_content)
  715. .setTitle(msg_title)
  716. .setContentType(content_type)
  717. .addExtra("data", extrasparam)
  718. .build())
  719. .setOptions(Options.newBuilder()
  720. //此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
  721. .setApnsProduction(true)
  722. //此字段是给开发者自己给推送编号,方便推送者分辨推送记录
  723. .setSendno(1)
  724. //此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天,单位为秒
  725. .setTimeToLive(86400)
  726. .build())
  727. .build();
  728. }
  729. public static void pushAline(String tag, String notification_title, String msg_content){
  730. ClientConfig config = ClientConfig.getInstance();
  731. JPushClient client = new JPushClient(MASTER_SECRET, APP_KEY, null, config);
  732. PushPayload payload = PushPayload.newBuilder()
  733. .setPlatform(Platform.android())//推送平台
  734. .setAudience(Audience.alias(tag))//推送目标
  735. .setNotification(Notification.newBuilder().addPlatformNotification(AndroidNotification.newBuilder()
  736. .setAlert(msg_content)
  737. .setTitle(notification_title).build()).build())//通知消息(标题,内容)
  738. .setOptions(Options.newBuilder().setApnsProduction(true).setTimeToLive(86400).build()//离线消息保存时间
  739. )
  740. .build();
  741. try {
  742. PushResult result = client.sendPush(payload);//推送
  743. System.out.println("推送结果:" + result.getResponseCode());
  744. } catch (Exception e) {
  745. e.printStackTrace();
  746. }
  747. }
  748. }

2.二类

  1. import java.util.Dictionary;
  2. import java.util.HashMap;
  3. import java.util.Hashtable;
  4. import java.util.List;
  5. import java.util.Map;
  6. import com.erenju.util.GlobleConfig;
  7. import com.google.gson.Gson;
  8. import com.google.gson.GsonBuilder;
  9. import com.xhgx.domain.RestInfo;
  10. import com.xhgx.web.util.JSONObject;
  11. import cn.jiguang.common.resp.APIConnectionException;
  12. import cn.jiguang.common.resp.APIRequestException;
  13. import cn.jpush.api.JPushClient;
  14. import cn.jpush.api.push.PushResult;
  15. import cn.jpush.api.push.model.Message;
  16. import cn.jpush.api.push.model.Options;
  17. import cn.jpush.api.push.model.Platform;
  18. import cn.jpush.api.push.model.PushPayload;
  19. import cn.jpush.api.push.model.audience.Audience;
  20. import cn.jpush.api.push.model.notification.AndroidNotification;
  21. import cn.jpush.api.push.model.notification.IosAlert;
  22. import cn.jpush.api.push.model.notification.IosNotification;
  23. import cn.jpush.api.push.model.notification.Notification;
  24. public class JpushUtil{
  25. /**
  26. * 推送通知:以广播形式推送给所有平台
  27. * @return
  28. */
  29. public static PushPayload buildPushObject_all_alias_alert(){
  30. return PushPayload.newBuilder()
  31. .setPlatform(Platform.all())//推送平台 :all代表全部 ,也可写具体的平台android或ios
  32. .setAudience(Audience.all())//推送目标:all表示以广播形式推送,所有用户都可接收到
  33. .setNotification(Notification.alert("测试广播推送!"))//推送到通知栏的内容
  34. .setOptions(Options.newBuilder()
  35. .setApnsProduction(true)//APNs是否为生产环境,false为开发环境
  36. .setSendno(1)//推送编号
  37. .setTimeToLive(86400)//指定本推送的离线保存时长(单位:秒),如果不传此字段则默认保存一天,最多指定保留十天
  38. .build())
  39. .build();
  40. }
  41. /**
  42. * 推送通知:根据alias推送给个人
  43. * @param alias
  44. * @param notification_title
  45. * @param msg_title
  46. * @param extrasparam
  47. * @return
  48. */
  49. public static PushPayload buildPushObject_all_alias_alertWithTitle(String alias,String notification_title, String msg_title, Map<String,String> extrasparam){
  50. String iosAlert = notification_title+":"+msg_title;
  51. //需要最新sdk版本
  52. // IosAlert iosAlert = IosAlert.newBuilder().setTitleAndBody("title", "alert body").build();
  53. //IosAlert.newBuilder().setTitleAndBody(notification_title, null, msg_title).setActionLocKey("PLAY").build()
  54. return PushPayload.newBuilder()
  55. //推送平台
  56. .setPlatform(Platform.all())
  57. //推送目标:all、tag、tag_and、tag_not、alias、registration_id等
  58. .setAudience(Audience.alias(alias))
  59. //通知
  60. .setNotification(Notification.newBuilder()
  61. .addPlatformNotification(AndroidNotification.newBuilder()//指定不同平台的推送内容
  62. .setTitle(notification_title)//标题
  63. .setAlert(msg_title)//内容
  64. //透传,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value
  65. 72 //另一种方式: addExtra(key,value)
  66. 73 .addExtras(extrasparam)
  67. 74 .build())
  68. 75 .addPlatformNotification(IosNotification.newBuilder()
  69. 76 .setAlert(iosAlert)//传一个IosAlert对象,指定apns title、title、subtitle等
  70. 77 .incrBadge(1)//此项是指定此推送的badge自动加1
  71. 78 //.setSound("sound.caf")//设置声音
  72. 79 //透传,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value
  73. 80 //另一种方式: addExtra(key,value)
  74. 81 .addExtras(extrasparam)
  75. 82 .setContentAvailable(true)//是否可以在锁屏状态下接收
  76. 83 .build())
  77. 84 .build())
  78. 85 //可选参数
  79. 86 .setOptions(Options.newBuilder()
  80. 87 .setApnsProduction(true)//APNs是否为生产环境,false为开发环境
  81. 88 .setSendno(1)//推送编号
  82. 89 .setTimeToLive(86400)//指定本推送的离线保存时长(单位:秒),如果不传此字段则默认保存一天,最多指定保留十天
  83. 90 .build())
  84. 91 .build();
  85. 92 }
  86. 93 /**
  87. 94 * 推送通知:根据alias同时推送给多个用户
  88. 95 * @param aliases
  89. 96 * @param notification_title
  90. 97 * @param msg_title
  91. 98 * @param extrasparam
  92. 99 * @return
  93. 100 */
  94. 101 public static PushPayload buildPushObject_all_aliases_alertWithTitle(List<String> aliases,String notification_title, String msg_title, Map<String,String> extrasparam){
  95. 102 String iosAlert = notification_title+":"+msg_title;
  96. 103 //需要最新sdk版本
  97. 104 // IosAlert iosAlert = IosAlert.newBuilder().setTitleAndBody("title", "alert body").build();
  98. 105 //IosAlert.newBuilder().setTitleAndBody(notification_title, null, msg_title).setActionLocKey("PLAY").build()
  99. 106 return PushPayload.newBuilder()
  100. 107 //推送平台
  101. 108 .setPlatform(Platform.all())
  102. 109 //推送目标:all、tag、tag_and、tag_not、alias、registration_id等
  103. 110 .setAudience(Audience.alias(aliases))
  104. 111 //通知
  105. 112 .setNotification(Notification.newBuilder()
  106. 113 .addPlatformNotification(AndroidNotification.newBuilder()//指定不同平台的推送内容
  107. 114 .setTitle(notification_title)//标题
  108. 115 .setAlert(msg_title)//内容
  109. 116 //透传,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value
  110. 117 //另一种方式: addExtra(key,value)
  111. 118 .addExtras(extrasparam)
  112. 119 .build())
  113. 120 .addPlatformNotification(IosNotification.newBuilder()
  114. 121 .setAlert(iosAlert)//传一个IosAlert对象,指定apns title、title、subtitle等
  115. 122 .incrBadge(1)//此项是指定此推送的badge自动加1
  116. 123 //.setSound("sound.caf")//设置声音
  117. 124 //透传,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value
  118. 125 //另一种方式: addExtra(key,value)
  119. 126 .addExtras(extrasparam)
  120. 127 .setContentAvailable(true)//是否可以在锁屏状态下接收
  121. 128 .build())
  122. 129 .build())
  123. 130 //可选参数
  124. 131 .setOptions(Options.newBuilder()
  125. 132 .setApnsProduction(true)//APNs是否为生产环境,false为开发环境
  126. 133 .setSendno(1)//推送编号
  127. 134 .setTimeToLive(86400)//指定本推送的离线保存时长(单位:秒),如果不传此字段则默认保存一天,最多指定保留十天
  128. 135 .build())
  129. 136 .build();
  130. 137 }
  131. 138
  132. 139 /**
  133. 140 * 推送通知和自定义消息:根据alias推给个人
  134. 141 * @param alias
  135. 142 * @param notification_title
  136. 143 * @param msg_title
  137. 144 * @param msg_content
  138. 145 * @param extrasparam
  139. 146 * @return
  140. 147 */
  141. 148 public static PushPayload buildPushObject_all_alias_alertAndmessage(String alias,String notification_title,String msg_title,String msg_content,Map<String, String> extrasparam ){
  142. 149 String iosAlert = notification_title+":"+msg_title;
  143. 150 //IosAlert.newBuilder().setTitleAndBody(notification_title, null, msg_title).setActionLocKey("PLAY").build()
  144. 151
  145. 152 return PushPayload.newBuilder()
  146. 153 //推送平台
  147. 154 .setPlatform(Platform.all())
  148. 155 //推送目标:all、tag、tag_and、tag_not、alias、registration_id等
  149. 156 .setAudience(Audience.alias(alias))
  150. 157 //通知
  151. 158 .setNotification(Notification.newBuilder()
  152. 159 .addPlatformNotification(AndroidNotification.newBuilder()//指定不同平台的推送内容
  153. 160 .setTitle(notification_title)//标题
  154. 161 .setAlert(msg_title)//内容
  155. 162 //透传,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value
  156. 163 //另一种方式: addExtra(key,value)
  157. 164 .addExtras(extrasparam)
  158. 165 .build())
  159. 166 .addPlatformNotification(IosNotification.newBuilder()
  160. 167 .setAlert(iosAlert)//传一个IosAlert对象,指定apns title、body、subtitle等
  161. 168 .incrBadge(1)//此项是指定此推送的badge自动加1
  162. 169 //.setSound("sound.caf")//设置声音
  163. 170 //透传,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value
  164. 171 //另一种方式: addExtra(key,value)
  165. 172 .addExtras(extrasparam)
  166. 173 //.setContentAvailable(true)//是否可以在锁屏状态下接收
  167. 174 .build())
  168. 175 .build())
  169. 176 //自定义消息
  170. 177 .setMessage(Message.newBuilder()
  171. 178 .setTitle(msg_title)//消息标题
  172. 179 .setMsgContent(msg_content)//消息内容本身
  173. 180 //.setContentType("json")//消息内容类型
  174. 181 .addExtras(extrasparam)//json格式的可选参数
  175. 182 .build())
  176. 183 //可选参数
  177. 184 .setOptions(Options.newBuilder()
  178. 185 .setApnsProduction(true)//APNs是否为生产环境,false为开发环境
  179. 186 .setSendno(1)//推送编号
  180. 187 .setTimeToLive(86400)//指定本推送的离线保存时长(单位:秒),如果不传此字段则默认保存一天,最多指定保留十天
  181. 188 .build())
  182. 189 .build();
  183. 190 }
  184. 191 /**
  185. 192 * 推送自定义消息:根据alias推给个人
  186. 193 * @param alias
  187. 194 * @param msg_title
  188. 195 * @param msg_content
  189. 196 * @param extrasparam
  190. 197 * @return
  191. 198 */
  192. 199 public static PushPayload buildPushObject_all_alias_message(String alias,String msg_title,String msg_content,Map<String, String> extrasparam ){
  193. 200
  194. 201 return PushPayload.newBuilder()
  195. 202 //推送平台
  196. 203 .setPlatform(Platform.all())
  197. 204 //推送目标:all、tag、tag_and、tag_not、alias、registration_id等
  198. 205 .setAudience(Audience.alias(alias))
  199. 206 //自定义消息
  200. 207 .setMessage(Message.newBuilder()
  201. 208 .setTitle(msg_title)//消息标题
  202. 209 .setMsgContent(msg_content)//消息内容本身
  203. 210 //.setContentType("json")//消息内容类型
  204. 211 .addExtras(extrasparam)//json格式的可选参数
  205. 212 .build())
  206. 213 //可选参数
  207. 214 .setOptions(Options.newBuilder()
  208. 215 .setApnsProduction(true)//APNs是否为生产环境,false为开发环境
  209. 216 .setSendno(1)//推送编号
  210. 217 .setTimeToLive(86400)//指定本推送的离线保存时长(单位:秒),如果不传此字段则默认保存一天,最多指定保留十天
  211. 218 .build())
  212. 219 .build();
  213. 220 }
  214. 221 /**
  215. 222 * 推送通知:根据tag推送给个人
  216. 223 * @param tag
  217. 224 * @param tag_add
  218. 225 * @param notification_title
  219. 226 * @param msg_title
  220. 227 * @param extrasparam
  221. 228 * @return
  222. 229 */
  223. 230 @SuppressWarnings("static-access")
  224. 231 public static PushPayload buildPushObject_all_tag_alertWithTitle(String tag,String tag_and,String notification_title, String msg_title, Map<String,String> extrasparam){
  225. 232 String iosAlert = notification_title+":"+msg_title;
  226. 233 //需要最新sdk版本
  227. 234 // IosAlert iosAlert = IosAlert.newBuilder().setTitleAndBody("title", "alert body").build();
  228. 235 //IosAlert.newBuilder().setTitleAndBody(notification_title, null, msg_title).setActionLocKey("PLAY").build()
  229. 236 return PushPayload.newBuilder()
  230. 237 //推送平台
  231. 238 .setPlatform(Platform.all())
  232. 239 //推送目标:all、tag、tag_and、tag_not、alias、registration_id等
  233. 240 .setAudience(Audience.tag(tag).tag_and(tag_and))
  234. 241 //通知
  235. 242 .setNotification(Notification.newBuilder()
  236. 243 .addPlatformNotification(AndroidNotification.newBuilder()//指定不同平台的推送内容
  237. 244 .setTitle(notification_title)//标题
  238. 245 .setAlert(msg_title)//内容
  239. 246 //透传,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value
  240. 247 //另一种方式: addExtra(key,value)
  241. 248 .addExtras(extrasparam)
  242. 249 .build())
  243. 250 .addPlatformNotification(IosNotification.newBuilder()
  244. 251 .setAlert(iosAlert)//传一个IosAlert对象,指定apns title、title、subtitle等
  245. 252 .incrBadge(1)//此项是指定此推送的badge自动加1
  246. 253 //.setSound("sound.caf")//设置声音
  247. 254 //透传,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value
  248. 255 //另一种方式: addExtra(key,value)
  249. 256 .addExtras(extrasparam)
  250. 257 //.setContentAvailable(true)//是否可以在锁屏状态下接收
  251. 258 .build())
  252. 259 .build())
  253. 260 //可选参数
  254. 261 .setOptions(Options.newBuilder()
  255. 262 .setApnsProduction(true)//APNs是否为生产环境,false为开发环境
  256. 263 .setSendno(1)//推送编号
  257. 264 .setTimeToLive(86400)//指定本推送的离线保存时长(单位:秒),如果不传此字段则默认保存一天,最多指定保留十天
  258. 265 .build())
  259. 266 .build();
  260. 267 }
  261. 268 /**
  262. 269 * 推送通知和自定义消息:根据tag推给个人
  263. 270 * @param tag
  264. 271 * @param tag_add
  265. 272 * @param notification_title
  266. 273 * @param msg_title
  267. 274 * @param msg_content
  268. 275 * @param extrasparam
  269. 276 * @return
  270. 277 */
  271. 278 @SuppressWarnings("static-access")
  272. 279 public static PushPayload buildPushObject_all_tag_alertAndmessage(String tag,String tag_and,String notification_title,String msg_title,String msg_content,Map<String, String> extrasparam ){
  273. 280 String iosAlert = notification_title+":"+msg_title;
  274. 281 //IosAlert.newBuilder().setTitleAndBody(notification_title, null, msg_title).setActionLocKey("PLAY").build()
  275. 282
  276. 283 return PushPayload.newBuilder()
  277. 284 //推送平台
  278. 285 .setPlatform(Platform.all())
  279. 286 //推送目标:all、tag、tag_and、tag_not、alias、registration_id等
  280. 287 .setAudience(Audience.tag(tag).tag_and(tag_and))
  281. 288 //通知
  282. 289 .setNotification(Notification.newBuilder()
  283. 290 .addPlatformNotification(AndroidNotification.newBuilder()//指定不同平台的推送内容
  284. 291 .setTitle(notification_title)//标题
  285. 292 .setAlert(msg_title)//内容
  286. 293 //透传,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value
  287. 294 //另一种方式: addExtra(key,value)
  288. 295 .addExtras(extrasparam)
  289. 296 .build())
  290. 297 .addPlatformNotification(IosNotification.newBuilder()
  291. 298 .setAlert(iosAlert)//传一个IosAlert对象,指定apns title、body、subtitle等
  292. 299 .incrBadge(1)//此项是指定此推送的badge自动加1
  293. 300 //.setSound("sound.caf")//设置声音
  294. 301 //透传,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value
  295. 302 //另一种方式: addExtra(key,value)
  296. 303 .addExtras(extrasparam)
  297. 304 //.setContentAvailable(true)//是否可以在锁屏状态下接收
  298. 305 .build())
  299. 306 .build())
  300. 307 //自定义消息
  301. 308 .setMessage(Message.newBuilder()
  302. 309 .setTitle(msg_title)//消息标题
  303. 310 .setMsgContent(msg_content)//消息内容本身
  304. 311 //.setContentType("json")//消息内容类型
  305. 312 .addExtras(extrasparam)//json格式的可选参数
  306. 313 .build())
  307. 314 //可选参数
  308. 315 .setOptions(Options.newBuilder()
  309. 316 .setApnsProduction(true)//APNs是否为生产环境,false为开发环境
  310. 317 .setSendno(1)//推送编号
  311. 318 .setTimeToLive(86400)//指定本推送的离线保存时长(单位:秒),如果不传此字段则默认保存一天,最多指定保留十天
  312. 319 .build())
  313. 320 .build();
  314. 321 }
  315. 322 /**
  316. 323 * 推送自定义消息:根据tag推给个人
  317. 324 * @param tag
  318. 325 * @param msg_title
  319. 326 * @param msg_content
  320. 327 * @param extrasparam
  321. 328 * @return
  322. 329 */
  323. 330 public static PushPayload buildPushObject_all_tags_message(String[] tag,String msg_title,String msg_content,Map<String, String> extrasparam ){
  324. 331
  325. 332 return PushPayload.newBuilder()
  326. 333 //推送平台
  327. 334 .setPlatform(Platform.all())
  328. 335 //推送目标:all、tag、tag_and、tag_not、alias、registration_id等
  329. 336 .setAudience(Audience.tag(tag))
  330. 337 //自定义消息
  331. 338 .setMessage(Message.newBuilder()
  332. 339 .setTitle(msg_title)//消息标题
  333. 340 .setMsgContent(msg_content)//消息内容本身
  334. //.setContentType("json")//消息内容类型
  335. .addExtras(extrasparam)//json格式的可选参数
  336. .build())
  337. //可选参数
  338. .setOptions(Options.newBuilder()
  339. .setApnsProduction(true)//APNs是否为生产环境,false为开发环境
  340. .setSendno(1)//推送编号
  341. .setTimeToLive(86400)//指定本推送的离线保存时长(单位:秒),如果不传此字段则默认保存一天,最多指定保留十天
  342. .build())
  343. .build();
  344. }
  345. }

3.三类

  1. #极光推送参数设定 yml
  2. jpush:
  3. appkey:
  4. masterSecret:
  5. #离线保存时间 7天 最长10天
  6. liveTime: 604800
  7. #推送开关
  8. enable: true
  1. @Component //配置类
  2. @ConfigurationProperties(prefix="jpush")
  3. public class JPushConfig {
  4. public static String APP_KEY;
  5. public static String MASTER_SECRET;
  6. public static long LIVE_TIME;
  7. /**
  8. * 是否开启推送
  9. */
  10. public static Boolean ENABLE;
  11. public void setAppKey(String appKey) {
  12. JPushConfig.APP_KEY = appKey;
  13. }
  14. public void setMasterSecret(String masterSecret) {
  15. JPushConfig.MASTER_SECRET = masterSecret;
  16. }
  17. public void setLiveTime(long liveTime) {
  18. JPushConfig.LIVE_TIME = liveTime;
  19. }
  20. public void setEnable(Boolean enable) {
  21. JPushConfig.ENABLE = enable;
  22. }
  1. public class JPushUtil {
  2. private static final Logger logger = LoggerFactory.getLogger(JPushUtil.class);
  3. /**
  4. * 消息自定义即时推送
  5. * @param jPushMsgVO
  6. * @return
  7. */
  8. public static PushLog messageCustomPush(JPushMsgVO jPushMsgVO) {
  9. JPushClient jpushClient = buildJPushClient(jPushMsgVO.getLiveTime());
  10. PushPayload payload = buildMessageCustomPushPayload(jPushMsgVO.getTitle(), jPushMsgVO.getContent(), jPushMsgVO.getExtrasMap(), jPushMsgVO.getPlatform(), jPushMsgVO.getPushType(), jPushMsgVO.getPushObject());
  11. PushResult result = null;
  12. PushLog pushLog = BeanUtils.copyResult(jPushMsgVO, PushLog::new);
  13. pushLog.setCreateTime(new Date());
  14. pushLog.setPushSort(PushSortEnum.MESSAGE.getCode());
  15. try {
  16. result = jpushClient.sendPush(payload);
  17. pushLog.setMsgId(String.valueOf(result.msg_id));
  18. logger.info("极光推送条件{},结果{}", payload,result);
  19. } catch (APIConnectionException e) {
  20. logger.error("极光推送连接错误,请稍后重试 ", e);
  21. logger.error("SendNo: " + payload.getSendno());
  22. } catch (APIRequestException e) {
  23. logger.error("极光服务器响应出错,请修复! ", e);
  24. logger.info("HTTP Status: {}", e.getStatus());
  25. logger.info("Error Code: {}", e.getErrorCode());
  26. logger.info("Error Message: {}", e.getErrorMessage());
  27. logger.error("SendNo: {}", payload.getSendno());
  28. pushLog.setMsgId(String.valueOf(e.getMsgId()));
  29. pushLog.setStatusCode(e.getErrorCode());
  30. pushLog.setErrMsg(e.getErrorMessage());
  31. } finally {
  32. pushLog.setPayload(payload.toString());
  33. pushLog.setSendNo(payload.getSendno());
  34. pushLog.setPushTime(new Date());
  35. }
  36. return pushLog;
  37. }
  38. /**
  39. * 消息自定义定时推送
  40. * @param jPushMsgVO
  41. * @return
  42. */
  43. public static PushLog messageCustomSchedulePush(JPushMsgVO jPushMsgVO) {
  44. JPushClient jpushClient = buildJPushClient(jPushMsgVO.getLiveTime());
  45. PushPayload payload = buildMessageCustomPushPayload(jPushMsgVO.getTitle(), jPushMsgVO.getContent(), jPushMsgVO.getExtrasMap(), jPushMsgVO.getPlatform(), jPushMsgVO.getPushType(), jPushMsgVO.getPushObject());
  46. ScheduleResult result = null;
  47. PushLog pushLog = BeanUtils.copyResult(jPushMsgVO, PushLog::new);
  48. pushLog.setCreateTime(new Date());
  49. pushLog.setStatusCode(-1);
  50. try {
  51. result = jpushClient.createSingleSchedule("CustomScheduleJPush", jPushMsgVO.getPushTime().toString(), payload);
  52. pushLog.setMsgId(result.getSchedule_id());
  53. logger.info("极光推送条件{},结果{}", payload,result);
  54. } catch (APIConnectionException e) {
  55. logger.error("极光推送连接错误,请稍后重试 ", e);
  56. logger.error("SendNo: " + payload.getSendno());
  57. } catch (APIRequestException e) {
  58. logger.error("极光服务器响应出错,请修复! ", e);
  59. logger.info("HTTP Status: {}", e.getStatus());
  60. logger.info("Error Code: {}", e.getErrorCode());
  61. logger.info("Error Message: {}", e.getErrorMessage());
  62. logger.error("SendNo: {}", payload.getSendno());
  63. pushLog.setStatusCode(e.getErrorCode());
  64. pushLog.setErrMsg(e.getErrorMessage());
  65. } finally {
  66. pushLog.setPayload(payload.toString());
  67. pushLog.setSendNo(payload.getSendno());
  68. pushLog.setPushTime(new Date());
  69. }
  70. return pushLog;
  71. }
  72. /**
  73. * 通知自定义即时推送
  74. * @param jPushMsgVO
  75. * @return 推送记录
  76. */
  77. public static PushLog notifyCustomPush(JPushMsgVO jPushMsgVO) {
  78. JPushClient jpushClient = buildJPushClient(jPushMsgVO.getLiveTime());
  79. //构造推送条件
  80. PushPayload payload = buildNotifyCustomPushPayload(jPushMsgVO.getTitle(), jPushMsgVO.getContent(), jPushMsgVO.getExtrasMap(), jPushMsgVO.getPlatform(), jPushMsgVO.getPushType(), jPushMsgVO.getPushObject());
  81. PushResult result = null;
  82. PushLog pushLog = BeanUtils.copyResult(jPushMsgVO, PushLog::new);
  83. pushLog.setCreateTime(new Date());
  84. pushLog.setStatusCode(-1);
  85. try {
  86. result = jpushClient.sendPush(payload);
  87. pushLog.setMsgId(String.valueOf(result.msg_id));
  88. pushLog.setPushMethod(PushMethodEnum.IMMEDIATE.getCode());
  89. pushLog.setStatusCode(result.statusCode);
  90. if(result.statusCode != 0){
  91. pushLog.setErrMsg(result.error.getMessage());
  92. }
  93. pushLog.setPayload(payload.toString());
  94. pushLog.setSendNo(payload.getSendno());
  95. logger.info("极光推送条件{},结果{}", payload,result);
  96. } catch (APIConnectionException e) {
  97. logger.error("极光推送连接错误,请稍后重试 ", e);
  98. logger.error("SendNo: " + payload.getSendno());
  99. } catch (APIRequestException e) {
  100. logger.error("极光服务器响应出错,请修复!", e);
  101. logger.info("HTTP Status: {}", e.getStatus());
  102. logger.info("Error Code: {}", e.getErrorCode());
  103. logger.info("Error Message: {}", e.getErrorMessage());
  104. logger.error("SendNo: {}", payload.getSendno());
  105. } finally {
  106. pushLog.setPushTime(new Date());
  107. }
  108. return pushLog;
  109. }
  110. /**
  111. * 通知自定义定时推送
  112. * @param jPushMsgVO
  113. * @return
  114. */
  115. public static PushLog notifyCustomSchedulePush(JPushMsgVO jPushMsgVO) {
  116. JPushClient jpushClient = buildJPushClient(jPushMsgVO.getLiveTime());
  117. PushPayload payload = buildNotifyCustomPushPayload(jPushMsgVO.getTitle(), jPushMsgVO.getContent(), jPushMsgVO.getExtrasMap(), jPushMsgVO.getPlatform(), jPushMsgVO.getPushType(), jPushMsgVO.getPushObject());
  118. ScheduleResult result = null;
  119. PushLog pushLog = new PushLog();
  120. pushLog.setPushMethod(PushMethodEnum.TIMING.getCode());
  121. pushLog.setCreateTime(new Date());
  122. pushLog.setStatusCode(-1);
  123. try {
  124. result = jpushClient.createSingleSchedule("CustomScheduleJPush", jPushMsgVO.getPushTime().toString(), payload);
  125. pushLog.setMsgId(result.getSchedule_id());
  126. pushLog.setPayload(payload.toString());
  127. pushLog.setSendNo(payload.getSendno());
  128. logger.info("极光推送条件{},结果{}", payload,result);
  129. } catch (APIConnectionException e) {
  130. logger.error("极光推送连接错误,请稍后重试 ", e);
  131. logger.error("SendNo: " + payload.getSendno());
  132. } catch (APIRequestException e) {
  133. logger.error("极光服务器响应出错,请修复! ", e);
  134. logger.info("HTTP Status: {}", e.getStatus());
  135. logger.info("Error Code: {}", e.getErrorCode());
  136. logger.info("Error Message: {}", e.getErrorMessage());
  137. logger.error("SendNo: {}", payload.getSendno());
  138. pushLog.setStatusCode(e.getErrorCode());
  139. pushLog.setErrMsg(e.getErrorMessage());
  140. } finally {
  141. pushLog.setPushTime(new Date());
  142. }
  143. return pushLog;
  144. }
  145. /**
  146. * 取消定时推送
  147. */
  148. public static boolean deleteSchedule(String scheduleId) {
  149. boolean result;
  150. try {
  151. JPushClient jPushClient = new JPushClient(JPushConfig.MASTER_SECRET, JPushConfig.APP_KEY);
  152. jPushClient.deleteSchedule(scheduleId);
  153. result = true;
  154. } catch (APIConnectionException e) {
  155. logger.error("Connection error. Should retry later. ", e);
  156. result = false;
  157. } catch (APIRequestException e) {
  158. logger.error("Error response from JPush server. Should review and fix it. ", e);
  159. logger.info("HTTP Status: {}", e.getStatus());
  160. logger.info("Error Code: {}", e.getErrorCode());
  161. logger.info("Error Message: {}", e.getErrorMessage());
  162. result = false;
  163. }
  164. return result;
  165. }
  166. /**
  167. * 构建自定义消息的推送消息对象
  168. *
  169. * @param title 推送消息标题
  170. * @param content 推送消息内容(为了单行显示全,尽量保持在22个汉字以下)
  171. * @param extrasMap 额外推送信息(不会显示在通知栏,传递数据用)
  172. * @param platform 推送的设备类型,默认全部类型
  173. * @param pushTypeEnum 推送方式,默认广播推送
  174. * @param pushObject PushTypeEnum为广播推送:此字段无意义;PushTypeEnum为别名推送:此字段为推送指定的别名;PushTypeEnum为标签推送:此字段为推送指定的标签
  175. * @return 推送消息对象
  176. */
  177. private static PushPayload buildMessageCustomPushPayload(String title, String content, Map<String, String> extrasMap, PushPlatformEnum platform, PushTypeEnum pushTypeEnum, List<String> pushObject) {
  178. // 批量删除数组中空元素
  179. return PushPayload.newBuilder()
  180. // 设置推送的设备类型
  181. .setPlatform(null == platform ? Platform.all() : getPlatform(platform))
  182. // 设置推送的受众
  183. .setAudience(getAudience(pushTypeEnum, pushObject))
  184. // 设置推送标题、内容、额外信息
  185. .setMessage(Message.newBuilder().setTitle(title).setMsgContent(content).addExtras(null == extrasMap ? new HashMap<>() : extrasMap).build())
  186. .build();
  187. }
  188. /**
  189. * 构建自定义的通知推送对象
  190. *
  191. * @param title 推送通知标题
  192. * @param content 推送通知内容(为了单行显示全,尽量保持在22个汉字以下)
  193. * @param extrasMap 额外推送信息(不会显示在通知栏,传递数据用)
  194. * @param platform 推送的设备类型,默认全部类型
  195. * @param PushTypeEnum 推送方式,默认广播推送
  196. * @param pushObject PushTypeEnum为广播推送:此字段无意义;PushTypeEnum为别名推送:此字段为推送指定的别名;PushTypeEnum为标签推送:此字段为推送指定的标签
  197. * @return 推送通知对象
  198. */
  199. private static PushPayload buildNotifyCustomPushPayload(String title, String content, Map<String, String> extrasMap, PushPlatformEnum platform, PushTypeEnum PushTypeEnum, List<String> pushObject) {
  200. extrasMap = extrasMap == null ? new HashMap<>() : extrasMap;
  201. return PushPayload.newBuilder().setPlatform(null == platform ? Platform.all() : getPlatform(platform))
  202. .setAudience(getAudience(PushTypeEnum, pushObject))
  203. .setNotification(Notification.newBuilder().setAlert(content)
  204. .addPlatformNotification(AndroidNotification.newBuilder().setTitle(title).addExtras(extrasMap).build())
  205. .addPlatformNotification(IosNotification.newBuilder().incrBadge(1).addExtras(extrasMap).build())
  206. .build())
  207. .build();
  208. }
  209. /**
  210. * 构建推送客户端
  211. */
  212. private static JPushClient buildJPushClient(Long liveTime) {
  213. ClientConfig clientConfig = ClientConfig.getInstance();
  214. clientConfig.setTimeToLive(liveTime == null ? JPushConfig.LIVE_TIME : liveTime);
  215. return new JPushClient(JPushConfig.MASTER_SECRET, JPushConfig.APP_KEY, null, clientConfig);
  216. }
  217. /**
  218. * 查询记录推送成功条数(暂未使用)
  219. *
  220. * @param msg_id 在推送返回结果PushResult中保存
  221. */
  222. public void countPush(String msg_id) {
  223. JPushClient jpushClient = new JPushClient(JPushConfig.MASTER_SECRET, JPushConfig.APP_KEY);
  224. try {
  225. ReceivedsResult result = jpushClient.getReportReceiveds(msg_id);
  226. ReceivedsResult.Received received = result.received_list.get(0);
  227. logger.debug("Android接受信息:" + received.android_received + "\n IOS端接受信息:" + received.ios_apns_sent);
  228. logger.debug("极光推送返回结果 - " + result);
  229. } catch (APIConnectionException e) {
  230. logger.error("极光推送连接错误,请稍后重试", e);
  231. } catch (APIRequestException e) {
  232. logger.error("检查错误,并修复推送请求", e);
  233. logger.info("HTTP Status: " + e.getStatus());
  234. logger.info("Error Code: " + e.getErrorCode());
  235. logger.info("Error Message: " + e.getErrorMessage());
  236. }
  237. }
  238. /**
  239. * 异步请求推送方式,使用NettyHttpClient,异步接口发送请求,通过回调函数可以获取推送成功与否情况
  240. */
  241. public void sendPushWithCallback(String title, String content, Map<String, String> extrasMap, PushPlatformEnum platform, PushTypeEnum PushTypeEnum, List<String> pushObject) {
  242. ClientConfig clientConfig = ClientConfig.getInstance();
  243. clientConfig.setTimeToLive(JPushConfig.LIVE_TIME);
  244. String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME);
  245. NettyHttpClient client = new NettyHttpClient(
  246. ServiceHelper.getBasicAuthorization(JPushConfig.APP_KEY, JPushConfig.MASTER_SECRET), null, clientConfig);
  247. try {
  248. URI uri = new URI(host + clientConfig.get(ClientConfig.PUSH_PATH));
  249. PushPayload payload = buildNotifyCustomPushPayload(title, content, extrasMap, platform, PushTypeEnum, pushObject);
  250. client.sendRequest(HttpMethod.POST, payload.toString(), uri, responseWrapper -> {
  251. if (200 == responseWrapper.responseCode) {
  252. logger.info("极光推送成功");
  253. } else {
  254. logger.info("极光推送失败,返回结果: " + responseWrapper.responseContent);
  255. }
  256. });
  257. } catch (URISyntaxException e) {
  258. e.printStackTrace();
  259. } finally {
  260. // 需要手动关闭Netty请求进程,否则会一直保留
  261. client.close();
  262. }
  263. }
  264. /**
  265. * 根据推送类型获取推送的受众
  266. */
  267. private static Audience getAudience(PushTypeEnum pushTypeEnum, List<String> pushObject) {
  268. switch (pushTypeEnum){
  269. // 别名推送
  270. case ALIAS:
  271. return Audience.alias(filterEmptyAndRepeatElement(pushObject));
  272. // 标签推送
  273. case TAG:
  274. return Audience.tag(filterEmptyAndRepeatElement(pushObject));
  275. //注册ID
  276. case REGISTRATION_ID:
  277. return Audience.registrationId(filterEmptyAndRepeatElement(pushObject));
  278. // 广播推送
  279. default:
  280. return Audience.all();
  281. }
  282. }
  283. /**
  284. * 过滤 空元素(需删除如:null,""," ")和重复的元素
  285. */
  286. private static List<String> filterEmptyAndRepeatElement(List<String> stringList) {
  287. return stringList.stream().filter(item -> item != null && !"".equals(item)).distinct().collect(Collectors.toList());
  288. }
  289. private static Platform getPlatform(PushPlatformEnum pushPlatformEnum){
  290. switch (pushPlatformEnum){
  291. case ALL:
  292. return Platform.all();
  293. case ANDROID:
  294. return Platform.android();
  295. case IOS:
  296. return Platform.ios();
  297. default:
  298. return Platform.android_ios();
  299. }
  300. }
  301. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/空白诗007/article/detail/950303
推荐阅读
相关标签
  

闽ICP备14008679号