JPush極光推送Java伺服器端例項

ldear發表於2017-08-21
1 import cn.jpush.api.JPushClient;
  2 import cn.jpush.api.common.resp.APIConnectionException;
  3 import cn.jpush.api.common.resp.APIRequestException;
  4 import cn.jpush.api.push.PushResult;
  5 import cn.jpush.api.push.model.Message;
  6 import cn.jpush.api.push.model.Options;
  7 import cn.jpush.api.push.model.Platform;
  8 import cn.jpush.api.push.model.PushPayload;
  9 import cn.jpush.api.push.model.audience.Audience;
 10 import cn.jpush.api.push.model.notification.*;
 11  
 12  
 13 public class JpushClientUtil {
 14  
 15     private final static String appKey = "此處為appKey";
 16  
 17     private final static String masterSecret = "此處為masterSecret";
 18  
 19     private static JPushClient jPushClient = new JPushClient(masterSecret,appKey);
 20  
 21     /**
 22      * 推送給裝置標識引數的使用者
 23      * @param registrationId 裝置標識
 24      * @param notification_title 通知內容標題
 25      * @param msg_title 訊息內容標題
 26      * @param msg_content 訊息內容
 27      * @param extrasparam 擴充套件欄位
 28      * @return 0推送失敗,1推送成功
 29      */
 30     public static int sendToRegistrationId( String registrationId,String notification_title, String msg_title, String msg_content, String extrasparam) {
 31         int result = 0;
 32         try {
 33             PushPayload pushPayload= JpushClientUtil.buildPushObject_all_registrationId_alertWithTitle(registrationId,notification_title,msg_title,msg_content,extrasparam);
 34             System.out.println(pushPayload);
 35             PushResult pushResult=jPushClient.sendPush(pushPayload);
 36             System.out.println(pushResult);
 37             if(pushResult.getResponseCode()==200){
 38                 result=1;
 39             }
 40         } catch (APIConnectionException e) {
 41             e.printStackTrace();
 42  
 43         } catch (APIRequestException e) {
 44             e.printStackTrace();
 45         }
 46  
 47          return result;
 48     }
 49  
 50     /**
 51      * 傳送給所有安卓使用者
 52      * @param notification_title 通知內容標題
 53      * @param msg_title 訊息內容標題
 54      * @param msg_content 訊息內容
 55      * @param extrasparam 擴充套件欄位
 56      * @return 0推送失敗,1推送成功
 57      */
 58     public static int sendToAllAndroid( String notification_title, String msg_title, String msg_content, String extrasparam) {
 59         int result = 0;
 60         try {
 61             PushPayload pushPayload= JpushClientUtil.buildPushObject_android_all_alertWithTitle(notification_title,msg_title,msg_content,extrasparam);
 62             System.out.println(pushPayload);
 63             PushResult pushResult=jPushClient.sendPush(pushPayload);
 64             System.out.println(pushResult);
 65             if(pushResult.getResponseCode()==200){
 66                 result=1;
 67             }
 68         } catch (Exception e) {
 69  
 70             e.printStackTrace();
 71         }
 72  
 73          return result;
 74     }
 75  
 76     /**
 77      * 傳送給所有IOS使用者
 78      * @param notification_title 通知內容標題
 79      * @param msg_title 訊息內容標題
 80      * @param msg_content 訊息內容
 81      * @param extrasparam 擴充套件欄位
 82      * @return 0推送失敗,1推送成功
 83      */
 84     public static int sendToAllIos(String notification_title, String msg_title, String msg_content, String extrasparam) {
 85         int result = 0;
 86         try {
 87             PushPayload pushPayload= JpushClientUtil.buildPushObject_ios_all_alertWithTitle(notification_title,msg_title,msg_content,extrasparam);
 88             System.out.println(pushPayload);
 89             PushResult pushResult=jPushClient.sendPush(pushPayload);
 90             System.out.println(pushResult);
 91             if(pushResult.getResponseCode()==200){
 92                 result=1;
 93             }
 94         } catch (Exception e) {
 95  
 96             e.printStackTrace();
 97         }
 98  
 99          return result;
100     }
101  
102     /**
103      * 傳送給所有使用者
104      * @param notification_title 通知內容標題
105      * @param msg_title 訊息內容標題
106      * @param msg_content 訊息內容
107      * @param extrasparam 擴充套件欄位
108      * @return 0推送失敗,1推送成功
109      */
110     public static int sendToAll( String notification_title, String msg_title, String msg_content, String extrasparam) {
111         int result = 0;
112         try {
113             PushPayload pushPayload= JpushClientUtil.buildPushObject_android_and_ios(notification_title,msg_title,msg_content,extrasparam);
114             System.out.println(pushPayload);
115             PushResult pushResult=jPushClient.sendPush(pushPayload);
116             System.out.println(pushResult);
117             if(pushResult.getResponseCode()==200){
118                 result=1;
119             }
120         } catch (Exception e) {
121  
122             e.printStackTrace();
123         }
124  
125         return result;
126     }
127  
128  
129  
130     public static PushPayload buildPushObject_android_and_ios(String notification_title, String msg_title, String msg_content, String extrasparam) {
131         return PushPayload.newBuilder()
132                 .setPlatform(Platform.android_ios())
133                 .setAudience(Audience.all())
134                 .setNotification(Notification.newBuilder()
135                         .setAlert(notification_title)
136                         .addPlatformNotification(AndroidNotification.newBuilder()
137                                 .setAlert(notification_title)
138                                 .setTitle(notification_title)
139                                 //此欄位為透傳欄位,不會顯示在通知欄。使用者可以通過此欄位來做一些定製需求,如特定的key傳要指定跳轉的頁面(value)
140                                 .addExtra("androidNotification extras key",extrasparam)
141                                 .build()
142                         )
143                         .addPlatformNotification(IosNotification.newBuilder()
144                                 //傳一個IosAlert物件,指定apns title、title、subtitle等
145                                 .setAlert(notification_title)
146                                 //直接傳alert
147                                 //此項是指定此推送的badge自動加1
148                                 .incrBadge(1)
149                                 //此欄位的值default表示系統預設聲音;傳sound.caf表示此推送以專案裡面打包的sound.caf聲音來提醒,
150                                 // 如果系統沒有此音訊則以系統預設聲音提醒;此欄位如果傳空字串,iOS9及以上的系統是無聲音提醒,以下的系統是預設聲音
151                                 .setSound("sound.caf")
152                                 //此欄位為透傳欄位,不會顯示在通知欄。使用者可以通過此欄位來做一些定製需求,如特定的key傳要指定跳轉的頁面(value)
153                                 .addExtra("iosNotification extras key",extrasparam)
154                                 //此項說明此推送是一個background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
155                                 // .setContentAvailable(true)
156  
157                                 .build()
158                         )
159                         .build()
160                 )
161                 //Platform指定了哪些平臺就會像指定平臺中符合推送條件的裝置進行推送。 jpush的自定義訊息,
162                 // sdk預設不做任何處理,不會有通知提示。建議看文件http://docs.jpush.io/guideline/faq/的
163                 // [通知與自定義訊息有什麼區別?]瞭解通知和自定義訊息的區別
164                 .setMessage(Message.newBuilder()
165                         .setMsgContent(msg_content)
166                         .setTitle(msg_title)
167                         .addExtra("message extras key",extrasparam)
168                         .build())
169  
170                 .setOptions(Options.newBuilder()
171                         //此欄位的值是用來指定本推送要推送的apns環境,false表示開發,true表示生產;對android和自定義訊息無意義
172                         .setApnsProduction(false)
173                         //此欄位是給開發者自己給推送編號,方便推送者分辨推送記錄
174                         .setSendno(1)
175                         //此欄位的值是用來指定本推送的離線儲存時長,如果不傳此欄位則預設儲存一天,最多指定保留十天,單位為秒
176                         .setTimeToLive(86400)
177                         .build()
178                 )
179                 .build();
180     }
181  
182     private static PushPayload buildPushObject_all_registrationId_alertWithTitle(String registrationId,String notification_title, String msg_title, String msg_content, String extrasparam) {
183  
184         System.out.println("----------buildPushObject_all_all_alert");
185         //建立一個IosAlert物件,可指定APNs的alert、title等欄位
186         //IosAlert iosAlert =  IosAlert.newBuilder().setTitleAndBody("title", "alert body").build();
187  
188         return PushPayload.newBuilder()
189                 //指定要推送的平臺,all代表當前應用配置了的所有平臺,也可以傳android等具體平臺
190                 .setPlatform(Platform.all())
191                 //指定推送的接收物件,all代表所有人,也可以指定已經設定成功的tag或alias或該應應用客戶端呼叫介面獲取到的registration id
192                 .setAudience(Audience.registrationId(registrationId))
193                 //jpush的通知,android的由jpush直接下發,iOS的由apns伺服器下發,Winphone的由mpns下發
194                 .setNotification(Notification.newBuilder()
195                         //指定當前推送的android通知
196                         .addPlatformNotification(AndroidNotification.newBuilder()
197  
198                                 .setAlert(notification_title)
199                                 .setTitle(notification_title)
200                                 //此欄位為透傳欄位,不會顯示在通知欄。使用者可以通過此欄位來做一些定製需求,如特定的key傳要指定跳轉的頁面(value)
201                                 .addExtra("androidNotification extras key",extrasparam)
202  
203                                 .build())
204                         //指定當前推送的iOS通知
205                         .addPlatformNotification(IosNotification.newBuilder()
206                                 //傳一個IosAlert物件,指定apns title、title、subtitle等
207                                 .setAlert(notification_title)
208                                 //直接傳alert
209                                 //此項是指定此推送的badge自動加1
210                                 .incrBadge(1)
211                                 //此欄位的值default表示系統預設聲音;傳sound.caf表示此推送以專案裡面打包的sound.caf聲音來提醒,
212                                 // 如果系統沒有此音訊則以系統預設聲音提醒;此欄位如果傳空字串,iOS9及以上的系統是無聲音提醒,以下的系統是預設聲音
213                                 .setSound("sound.caf")
214                                 //此欄位為透傳欄位,不會顯示在通知欄。使用者可以通過此欄位來做一些定製需求,如特定的key傳要指定跳轉的頁面(value)
215                                 .addExtra("iosNotification extras key",extrasparam)
216                                 //此項說明此推送是一個background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
217                                 //取消此註釋,訊息推送時ios將無法在鎖屏情況接收
218                                 // .setContentAvailable(true)
219  
220                                 .build())
221  
222  
223                         .build())
224                 //Platform指定了哪些平臺就會像指定平臺中符合推送條件的裝置進行推送。 jpush的自定義訊息,
225                 // sdk預設不做任何處理,不會有通知提示。建議看文件http://docs.jpush.io/guideline/faq/的
226                 // [通知與自定義訊息有什麼區別?]瞭解通知和自定義訊息的區別
227                 .setMessage(Message.newBuilder()
228  
229                         .setMsgContent(msg_content)
230  
231                         .setTitle(msg_title)
232  
233                         .addExtra("message extras key",extrasparam)
234  
235                         .build())
236  
237                 .setOptions(Options.newBuilder()
238                         //此欄位的值是用來指定本推送要推送的apns環境,false表示開發,true表示生產;對android和自定義訊息無意義
239                         .setApnsProduction(false)
240                         //此欄位是給開發者自己給推送編號,方便推送者分辨推送記錄
241                         .setSendno(1)
242                         //此欄位的值是用來指定本推送的離線儲存時長,如果不傳此欄位則預設儲存一天,最多指定保留十天;
243                         .setTimeToLive(86400)
244  
245                         .build())
246  
247                 .build();
248  
249     }
250  
251     private static PushPayload buildPushObject_android_all_alertWithTitle(String notification_title, String msg_title, String msg_content, String extrasparam) {
252         System.out.println("----------buildPushObject_android_registrationId_alertWithTitle");
253         return PushPayload.newBuilder()
254                 //指定要推送的平臺,all代表當前應用配置了的所有平臺,也可以傳android等具體平臺
255                 .setPlatform(Platform.android())
256                 //指定推送的接收物件,all代表所有人,也可以指定已經設定成功的tag或alias或該應應用客戶端呼叫介面獲取到的registration id
257                 .setAudience(Audience.all())
258                 //jpush的通知,android的由jpush直接下發,iOS的由apns伺服器下發,Winphone的由mpns下發
259                 .setNotification(Notification.newBuilder()
260                         //指定當前推送的android通知
261                         .addPlatformNotification(AndroidNotification.newBuilder()
262                                 .setAlert(notification_title)
263                                 .setTitle(notification_title)
264                                 //此欄位為透傳欄位,不會顯示在通知欄。使用者可以通過此欄位來做一些定製需求,如特定的key傳要指定跳轉的頁面(value)
265                                 .addExtra("androidNotification extras key",extrasparam)
266                                 .build())
267                         .build()
268                 )
269                 //Platform指定了哪些平臺就會像指定平臺中符合推送條件的裝置進行推送。 jpush的自定義訊息,
270                 // sdk預設不做任何處理,不會有通知提示。建議看文件http://docs.jpush.io/guideline/faq/的
271                 // [通知與自定義訊息有什麼區別?]瞭解通知和自定義訊息的區別
272                 .setMessage(Message.newBuilder()
273                         .setMsgContent(msg_content)
274                         .setTitle(msg_title)
275                         .addExtra("message extras key",extrasparam)
276                         .build())
277  
278                 .setOptions(Options.newBuilder()
279                         //此欄位的值是用來指定本推送要推送的apns環境,false表示開發,true表示生產;對android和自定義訊息無意義
280                         .setApnsProduction(false)
281                         //此欄位是給開發者自己給推送編號,方便推送者分辨推送記錄
282                         .setSendno(1)
283                         //此欄位的值是用來指定本推送的離線儲存時長,如果不傳此欄位則預設儲存一天,最多指定保留十天,單位為秒
284                         .setTimeToLive(86400)
285                         .build())
286                 .build();
287     }
288  
289     private static PushPayload buildPushObject_ios_all_alertWithTitle( String notification_title, String msg_title, String msg_content, String extrasparam) {
290         System.out.println("----------buildPushObject_ios_registrationId_alertWithTitle");
291         return PushPayload.newBuilder()
292                 //指定要推送的平臺,all代表當前應用配置了的所有平臺,也可以傳android等具體平臺
293                 .setPlatform(Platform.ios())
294                 //指定推送的接收物件,all代表所有人,也可以指定已經設定成功的tag或alias或該應應用客戶端呼叫介面獲取到的registration id
295                 .setAudience(Audience.all())
296                 //jpush的通知,android的由jpush直接下發,iOS的由apns伺服器下發,Winphone的由mpns下發
297                 .setNotification(Notification.newBuilder()
298                         //指定當前推送的android通知
299                         .addPlatformNotification(IosNotification.newBuilder()
300                                 //傳一個IosAlert物件,指定apns title、title、subtitle等
301                                 .setAlert(notification_title)
302                                 //直接傳alert
303                                 //此項是指定此推送的badge自動加1
304                                 .incrBadge(1)
305                                 //此欄位的值default表示系統預設聲音;傳sound.caf表示此推送以專案裡面打包的sound.caf聲音來提醒,
306                                 // 如果系統沒有此音訊則以系統預設聲音提醒;此欄位如果傳空字串,iOS9及以上的系統是無聲音提醒,以下的系統是預設聲音
307                                 .setSound("sound.caf")
308                                 //此欄位為透傳欄位,不會顯示在通知欄。使用者可以通過此欄位來做一些定製需求,如特定的key傳要指定跳轉的頁面(value)
309                                 .addExtra("iosNotification extras key",extrasparam)
310                                 //此項說明此推送是一個background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
311                                // .setContentAvailable(true)
312  
313                                 .build())
314                         .build()
315                 )
316                 //Platform指定了哪些平臺就會像指定平臺中符合推送條件的裝置進行推送。 jpush的自定義訊息,
317                 // sdk預設不做任何處理,不會有通知提示。建議看文件http://docs.jpush.io/guideline/faq/的
318                 // [通知與自定義訊息有什麼區別?]瞭解通知和自定義訊息的區別
319                 .setMessage(Message.newBuilder()
320                         .setMsgContent(msg_content)
321                         .setTitle(msg_title)
322                         .addExtra("message extras key",extrasparam)
323                         .build())
324  
325                 .setOptions(Options.newBuilder()
326                         //此欄位的值是用來指定本推送要推送的apns環境,false表示開發,true表示生產;對android和自定義訊息無意義
327                         .setApnsProduction(false)
328                         //此欄位是給開發者自己給推送編號,方便推送者分辨推送記錄
329                         .setSendno(1)
330                         //此欄位的值是用來指定本推送的離線儲存時長,如果不傳此欄位則預設儲存一天,最多指定保留十天,單位為秒
331                         .setTimeToLive(86400)
332                         .build())
333                 .build();
334     }
335  
336 //    public static void main(String[] args){
337 //        if(JpushClientUtil.sendToAllIos("testIos","testIos","this is a ios Dev test","")==1){
338 //            System.out.println("success");
339 //        }
340 //    }
341 }
342  
343  
344  
345 public class Jdpush {  
346      protected static final Logger LOG = LoggerFactory.getLogger(Jdpush.class);  
347   
348      // demo App defined in resources/jpush-api.conf   
349   
350     public static final String TITLE = "申通快遞";  
351     public static final String ALERT = "祝大家新春快樂";  
352     public static final String MSG_CONTENT = "申通快遞祝新老客戶新春快樂";  
353     public static final String REGISTRATION_ID = "0900e8d85ef";  
354     public static final String TAG = "tag_api";  
355       
356     public  static JPushClient jpushClient=null;  
357       
358     public static void testSendPush(String appKey ,String masterSecret) {  
359           
360           
361           
362          jpushClient = new JPushClient(masterSecret, appKey, 3);  
363           
364         // HttpProxy proxy = new HttpProxy("localhost", 3128);  
365         // Can use this https proxy: https://github.com/Exa-Networks/exaproxy  
366          
367           
368         // For push, all you need do is to build PushPayload object.  
369         //PushPayload payload = buildPushObject_all_all_alert();  
370          //生成推送的內容,這裡我們先測試全部推送  
371         PushPayload payload=buildPushObject_all_alias_alert();  
372           
373           
374         try {  
375             System.out.println(payload.toString());  
376             PushResult result = jpushClient.sendPush(payload);  
377             System.out.println(result+"................................");  
378               
379             LOG.info("Got result - " + result);  
380               
381         } catch (APIConnectionException e) {  
382             LOG.error("Connection error. Should retry later. ", e);  
383               
384         } catch (APIRequestException e) {  
385             LOG.error("Error response from JPush server. Should review and fix it. ", e);  
386             LOG.info("HTTP Status: " + e.getStatus());  
387             LOG.info("Error Code: " + e.getErrorCode());  
388             LOG.info("Error Message: " + e.getErrorMessage());  
389             LOG.info("Msg ID: " + e.getMsgId());  
390         }  
391     }  
392       
393     public static PushPayload buildPushObject_all_all_alert() {  
394         return PushPayload.alertAll(ALERT);  
395     }  
396       
397     public static PushPayload buildPushObject_all_alias_alert() {  
398         return PushPayload.newBuilder()  
399                 .setPlatform(Platform.all())//設定接受的平臺  
400                 .setAudience(Audience.all())//Audience設定為all,說明採用廣播方式推送,所有使用者都可以接收到  
401                 .setNotification(Notification.alert(ALERT))  
402                 .build();  
403     }  
404       
405     public static PushPayload buildPushObject_android_tag_alertWithTitle() {  
406         return PushPayload.newBuilder()  
407                 .setPlatform(Platform.android())  
408                 .setAudience(Audience.all())  
409                 .setNotification(Notification.android(ALERT, TITLE, null))  
410                 .build();  
411     }  
412       
413     public static PushPayload buildPushObject_android_and_ios() {  
414         return PushPayload.newBuilder()  
415                 .setPlatform(Platform.android_ios())  
416                 .setAudience(Audience.tag("tag1"))  
417                 .setNotification(Notification.newBuilder()  
418                         .setAlert("alert content")  
419                         .addPlatformNotification(AndroidNotification.newBuilder()  
420                                 .setTitle("Android Title").build())  
421                         .addPlatformNotification(IosNotification.newBuilder()  
422                                 .incrBadge(1)  
423                                 .addExtra("extra_key", "extra_value").build())  
424                         .build())  
425                 .build();  
426     }  
427       
428     public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage() {  
429         return PushPayload.newBuilder()  
430                 .setPlatform(Platform.ios())  
431                 .setAudience(Audience.tag_and("tag1", "tag_all"))  
432                 .setNotification(Notification.newBuilder()  
433                         .addPlatformNotification(IosNotification.newBuilder()  
434                                 .setAlert(ALERT)  
435                                 .setBadge(5)  
436                                 .setSound("happy")  
437                                 .addExtra("from", "JPush")  
438                                 .build())  
439                         .build())  
440                  .setMessage(Message.content(MSG_CONTENT))  
441                  .setOptions(Options.newBuilder()  
442                          .setApnsProduction(true)  
443                          .build())  
444                  .build();  
445     }  
446       
447     public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {  
448         return PushPayload.newBuilder()  
449                 .setPlatform(Platform.android_ios())  
450                 .setAudience(Audience.newBuilder()  
451                         .addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))  
452                         .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))  
453                         .build())  
454                 .setMessage(Message.newBuilder()  
455                         .setMsgContent(MSG_CONTENT)  
456                         .addExtra("from", "JPush")  
457                         .build())  
458                 .build();  
459     }  
460 }  

相關文章