JPush极光推送Java服务器端实例

Posted 神啊bin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JPush极光推送Java服务器端实例相关的知识,希望对你有一定的参考价值。

import cn.jpush.api.JPushClient;
import cn.jpush.api.common.resp.APIConnectionException;
import cn.jpush.api.common.resp.APIRequestException;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.*;
 
 
public class JpushClientUtil {
 
    private final static String appKey = "此处为appKey";
 
    private final static String masterSecret = "此处为masterSecret";
 
    private static JPushClient jPushClient = new JPushClient(masterSecret,appKey);
 
    /**
     * 推送给设备标识参数的用户
     * @param registrationId 设备标识
     * @param notification_title 通知内容标题
     * @param msg_title 消息内容标题
     * @param msg_content 消息内容
     * @param extrasparam 扩展字段
     * @return 0推送失败,1推送成功
     */
    public static int sendToRegistrationId( String registrationId,String notification_title, String msg_title, String msg_content, String extrasparam) {
        int result = 0;
        try {
            PushPayload pushPayload= JpushClientUtil.buildPushObject_all_registrationId_alertWithTitle(registrationId,notification_title,msg_title,msg_content,extrasparam);
            System.out.println(pushPayload);
            PushResult pushResult=jPushClient.sendPush(pushPayload);
            System.out.println(pushResult);
            if(pushResult.getResponseCode()==200){
                result=1;
            }
        catch (APIConnectionException e) {
            e.printStackTrace();
 
        catch (APIRequestException e) {
            e.printStackTrace();
        }
 
         return result;
    }
 
    /**
     * 发送给所有安卓用户
     * @param notification_title 通知内容标题
     * @param msg_title 消息内容标题
     * @param msg_content 消息内容
     * @param extrasparam 扩展字段
     * @return 0推送失败,1推送成功
     */
    public static int sendToAllandroid( String notification_title, String msg_title, String msg_content, String extrasparam) {
        int result = 0;
        try {
            PushPayload pushPayload= JpushClientUtil.buildPushObject_android_all_alertWithTitle(notification_title,msg_title,msg_content,extrasparam);
            System.out.println(pushPayload);
            PushResult pushResult=jPushClient.sendPush(pushPayload);
            System.out.println(pushResult);
            if(pushResult.getResponseCode()==200){
                result=1;
            }
        catch (Exception e) {
 
            e.printStackTrace();
        }
 
         return result;
    }
 
    /**
     * 发送给所有ios用户
     * @param notification_title 通知内容标题
     * @param msg_title 消息内容标题
     * @param msg_content 消息内容
     * @param extrasparam 扩展字段
     * @return 0推送失败,1推送成功
     */
    public static int sendToAllIos(String notification_title, String msg_title, String msg_content, String extrasparam) {
        int result = 0;
        try {
            PushPayload pushPayload= JpushClientUtil.buildPushObject_ios_all_alertWithTitle(notification_title,msg_title,msg_content,extrasparam);
            System.out.println(pushPayload);
            PushResult pushResult=jPushClient.sendPush(pushPayload);
            System.out.println(pushResult);
            if(pushResult.getResponseCode()==200){
                result=1;
            }
        catch (Exception e) {
 
            e.printStackTrace();
        }
 
         return result;
    }
 
    /**
     * 发送给所有用户
     * @param notification_title 通知内容标题
     * @param msg_title 消息内容标题
     * @param msg_content 消息内容
     * @param extrasparam 扩展字段
     * @return 0推送失败,1推送成功
     */
    public static int sendToAll( String notification_title, String msg_title, String msg_content, String extrasparam) {
        int result = 0;
        try {
            PushPayload pushPayload= JpushClientUtil.buildPushObject_android_and_ios(notification_title,msg_title,msg_content,extrasparam);
            System.out.println(pushPayload);
            PushResult pushResult=jPushClient.sendPush(pushPayload);
            System.out.println(pushResult);
            if(pushResult.getResponseCode()==200){
                result=1;
            }
        catch (Exception e) {
 
            e.printStackTrace();
        }
 
        return result;
    }
 
 
 
    public static PushPayload buildPushObject_android_and_ios(String notification_title, String msg_title, String msg_content, String extrasparam) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.all())
                .setNotification(Notification.newBuilder()
                        .setAlert(notification_title)
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(notification_title)
                                .setTitle(notification_title)
                                //此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
                                .addExtra("androidNotification extras key",extrasparam)
                                .build()
                        )
                        .addPlatformNotification(IosNotification.newBuilder()
                                //传一个IosAlert对象,指定apns title、title、subtitle等
                                .setAlert(notification_title)
                                //直接传alert
                                //此项是指定此推送的badge自动加1
                                .incrBadge(1)
                                //此字段的值default表示系统默认声音;传sound.caf表示此推送以项目里面打包的sound.caf声音来提醒,
                                // 如果系统没有此音频则以系统默认声音提醒;此字段如果传空字符串,iOS9及以上的系统是无声音提醒,以下的系统是默认声音
                                .setSound("sound.caf")
                                //此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
                                .addExtra("iosNotification extras key",extrasparam)
                                //此项说明此推送是一个background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
                                // .setContentAvailable(true)
 
                                .build()
                        )
                        .build()
                )
                //Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
                // sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
                // [通知与自定义消息有什么区别?]了解通知和自定义消息的区别
                .setMessage(Message.newBuilder()
                        .setMsgContent(msg_content)
                        .setTitle(msg_title)
                        .addExtra("message extras key",extrasparam)
                        .build())
 
                .setOptions(Options.newBuilder()
                        //此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
                        .setApnsProduction(false)
                        //此字段是给开发者自己给推送编号,方便推送者分辨推送记录
                        .setSendno(1)
                        //此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天,单位为秒
                        .setTimeToLive(86400)
                        .build()
                )
                .build();
    }
 
    private static PushPayload buildPushObject_all_registrationId_alertWithTitle(String registrationId,String notification_title, String msg_title, String msg_content, String extrasparam) {
 
        System.out.println("----------buildPushObject_all_all_alert");
        //创建一个IosAlert对象,可指定APNs的alert、title等字段
        //IosAlert iosAlert =  IosAlert.newBuilder().setTitleAndBody("title", "alert body").build();
 
        return PushPayload.newBuilder()
                //指定要推送的平台,all代表当前应用配置了的所有平台,也可以传android等具体平台
                .setPlatform(Platform.all())
                //指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
                .setAudience(Audience.registrationId(registrationId))
                //jpush的通知,android的由jpush直接下发,iOS的由apns服务器下发,Winphone的由mpns下发
                .setNotification(Notification.newBuilder()
                        //指定当前推送的android通知
                        .addPlatformNotification(AndroidNotification.newBuilder()
 
                                .setAlert(notification_title)
                                .setTitle(notification_title)
                                //此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
                                .addExtra("androidNotification extras key",extrasparam)
 
                                .build())
                        //指定当前推送的iOS通知
                        .addPlatformNotification(IosNotification.newBuilder()
                                //传一个IosAlert对象,指定apns title、title、subtitle等
                                .setAlert(notification_title)
                                //直接传alert
                                //此项是指定此推送的badge自动加1
                                .incrBadge(1)
                                //此字段的值default表示系统默认声音;传sound.caf表示此推送以项目里面打包的sound.caf声音来提醒,
                                // 如果系统没有此音频则以系统默认声音提醒;此字段如果传空字符串,iOS9及以上的系统是无声音提醒,以下的系统是默认声音
                                .setSound("sound.caf")
                                //此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
                                .addExtra("iosNotification extras key",extrasparam)
                                //此项说明此推送是一个background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
                                //取消此注释,消息推送时ios将无法在锁屏情况接收
                                // .setContentAvailable(true)
 
                                .build())
 
 
                        .build())
                //Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
                // sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
                // [通知与自定义消息有什么区别?]了解通知和自定义消息的区别
                .setMessage(Message.newBuilder()
 
                        .setMsgContent(msg_content)
 
                        .setTitle(msg_title)
 
                        .addExtra("message extras key",extrasparam)
 
                        .build())
 
                .setOptions(Options.newBuilder()
                        //此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
                        .setApnsProduction(false)
                        //此字段是给开发者自己给推送编号,方便推送者分辨推送记录
                        .setSendno(1)
                        //此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天;
                        .setTimeToLive(86400)
 
                        .build())
 
                .build();
 
    }
 
    private static PushPayload buildPushObject_android_all_alertWithTitle(String notification_title, String msg_title, String msg_content, String extrasparam) {
        System.out.println("----------buildPushObject_android_registrationId_alertWithTitle");
        return PushPayload.newBuilder()
                //指定要推送的平台,all代表当前应用配置了的所有平台,也可以传android等具体平台
                .setPlatform(Platform.android())
                //指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
                .setAudience(Audience.all())
                //jpush的通知,android的由jpush直接下发,iOS的由apns服务器下发,Winphone的由mpns下发
                .setNotification(Notification.newBuilder()
                        //指定当前推送的android通知
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(notification_title)
                                .setTitle(notification_title)
                                //此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
                                .addExtra("androidNotification extras key",extrasparam)
                                .build())
                        .build()
                )
                //Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
                // sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
                // [通知与自定义消息有什么区别?]了解通知和自定义消息的区别
                .setMessage(Message.newBuilder()
                        .setMsgContent(msg_content)
                        .setTitle(msg_title)
                        .addExtra("message extras key",extrasparam)
                        .build())
 
                .setOptions(Options.newBuilder()
                        //此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
                        .setApnsProduction(false)
                        //此字段是给开发者自己给推送编号,方便推送者分辨推送记录
                        .setSendno(1)
                        //此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天,单位为秒
                        .setTimeToLive(86400)
                        .build())
                .build();
    }
 
    private static PushPayload buildPushObject_ios_all_alertWithTitle( String notification_title, String msg_title, String msg_content, String extrasparam) {
        System.out.println("----------buildPushObject_ios_registrationId_alertWithTitle");
        return PushPayload.newBuilder()
                //指定要推送的平台,all代表当前应用配置了的所有平台,也可以传android等具体平台
                .setPlatform(Platform.ios())
                //指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
                .setAudience(Audience.all())
                //jpush的通知,android的由jpush直接下发,iOS的由apns服务器下发,Winphone的由mpns下发
                .setNotification(Notification.newBuilder()
                        //指定当前推送的android通知
                        .addPlatformNotification(IosNotification.newBuilder()
                                //传一个IosAlert对象,指定apns title、title、subtitle等
                                .setAlert(notification_title)
                                //直接传alert
                                //此项是指定此推送的badge自动加1
                                .incrBadge(1)
                                //此字段的值default表示系统默认声音;传sound.caf表示此推送以项目里面打包的sound.caf声音来提醒,
                                // 如果系统没有此音频则以系统默认声音提醒;此字段如果传空字符串,iOS9及以上的系统是无声音提醒,以下的系统是默认声音
                                .setSound("sound.caf")
                                //此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
                                .addExtra("iosNotification extras key",extrasparam)
                                //此项说明此推送是一个background推送,想了解background看:http://docs.jpush.io/client/ios_tutorials/#ios-7-background-remote-notification
                               // .setContentAvailable(true)
 
                                .build())
                        .build()
                )
                //Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
                // sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
                // [通知与自定义消息有什么区别?]了解通知和自定义消息的区别
                .setMessage(Message.newBuilder()
                        .setMsgContent(msg_content)
                        .setTitle(msg_title)
                        .addExtra("message extras key",extrasparam)
                        .build())
 
                .setOptions(Options.newBuilder()
                        //此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
                        .setApnsProduction(false)
                        //此字段是给开发者自己给推送编号,方便推送者分辨推送记录
                        .setSendno(1)
                        //此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天,单位为秒
                        .setTimeToLive(86400)
                        .build())
                .build();
    }
 
//    public static void main(String[] args){
//        if(JpushClientUtil.sendToAllIos("testIos","testIos","this is a ios Dev test","")==1){
//            System.out.println("success");
//        }
//    }
}
 
 
 
  1. public class Jdpush {  
  2.      protected static final Logger LOG = LoggerFactory.getLogger(Jdpush.class);  
  3.   
  4.      // demo App defined in resources/jpush-api.conf   
  5.   
  6.     public static final String TITLE = "申通快递";  
  7.     public static final String ALERT = "祝大家新春快乐";  
  8.     public static final String MSG_CONTENT = "申通快递祝新老客户新春快乐";  
  9.     public static final String REGISTRATION_ID = "0900e8d85ef";  
  10.     public static final String TAG = "tag_api";  
  11.       
  12.     public  static JPushClient jpushClient=null;  
  13.       
  14.     public static void testSendPush(String appKey ,String masterSecret) {  
  15.           
  16.           
  17.           
  18.          jpushClient = new JPushClient(masterSecret, appKey, 3);  
  19.           
  20.         // HttpProxy proxy = new HttpProxy("localhost", 3128);  
  21.         // Can use this https proxy: https://github.com/Exa-Networks/exaproxy  
  22.          
  23.           
  24.         // For push, all you need do is to build PushPayload object.  
  25.         //PushPayload payload = buildPushObject_all_all_alert();  
  26.          //生成推送的内容,这里我们先测试全部推送  
  27.         PushPayload payload=buildPushObject_all_alias_alert();  
  28.           
  29.           
  30.         try {  
  31.             System.out.println(payload.toString());  
  32.             PushResult result = jpushClient.sendPush(payload);  
  33.             System.out.println(result+"................................");  
  34.               
  35.             LOG.info("Got result - " + result);  
  36.               
  37.         } catch (APIConnectionException e) {  
  38.             LOG.error("Connection error. Should retry later. ", e);  
  39.               
  40.         } catch (APIRequestException e) {  
  41.             LOG.error("Error response from JPush server. Should review and fix it. ", e);  
  42.             LOG.info("HTTP Status: " + e.getStatus());  
  43.             LOG.info("Error Code: " + e.getErrorCode());  
  44.             LOG.info("Error Message: " + e.getErrorMessage());  
  45.             LOG.info("Msg ID: " + e.getMsgId());  
  46.         }  
  47.     }  
  48.       
  49.     public static PushPayload buildPushObject_all_all_alert() {  
  50.         return PushPayload.alertAll(ALERT);  
  51.     }  
  52.       
  53.     public static PushPayload buildPushObject_all_alias_alert() {  
  54.         return PushPayload.newBuilder()  
  55.                 .setPlatform(Platform.all())//设置接受的平台  
  56.                 .setAudience(Audience.all())//Audience设置为all,说明采用广播方式推送,所有用户都可以接收到  
  57.                 .setNotification(Notification.alert(ALERT))  
  58.                 .build();  
  59.     }  
  60.       
  61.     public static PushPayload buildPushObject_android_tag_alertWithTitle() {  
  62.         return PushPayload.newBuilder()  
  63.                 .setPlatform(Platform.android())  
  64.                 .setAudience(Audience.all())  
  65.                 .setNotification(Notification.android(ALERT, TITLE, null))  
  66.                 .build();  
  67.     }  
  68.       
  69.     public static PushPayload buildPushObject_android_and_ios() {  
  70.         return PushPayload.newBuilder()  
  71.                 .setPlatform(Platform.android_ios())  
  72.                 .setAudience(Audience.tag("tag1"))  
  73.                 .setNotification(Notification.newBuilder()  
  74.                         .setAlert("alert content")  
  75.                         .addPlatformNotification(AndroidNotification.newBuilder()  
  76.                                 .setTitle("Android Title").build())  
  77.                         .addPlatformNotification(IosNotification.newBuilder()  
  78.                                 .incrBadge(1)  
  79.                                 .addExtra("extra_key", "extra_value").build())  
  80.                         .build())  
  81.                 .build();  
  82.     }  
  83.       
  84.     public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage() {  
  85.         return PushPayload.newBuilder()  
  86.                 .setPlatform(Platform.ios())  
  87.                 .setAudience(Audience.tag_and("tag1", "tag_all"))  
  88.                 .setNotification(Notification.newBuilder()  
  89.                         .addPlatformNotification(IosNotification.newBuilder()  
  90.                                 .setAlert(ALERT)  
  91.                                 .setBadge(5)  
  92.                                 .setSound("happy")  
  93.                                 .addExtra("from", "JPush")  
  94.                                 .build())  
  95.                         .build())  
  96.                  .setMessage(Message.content(MSG_CONTENT))  
  97.                  .setOptions(Options.newBuilder()  
  98.                          .setApnsProduction(true)  
  99.                          .build())  
  100.                  .build();  
  101.     }  
  102.       
  103.     public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {  
  104.         return PushPayload.newBuilder()  
  105.                 .setPlatform(Platform.android_ios())  
  106.                 .setAudience(Audience.newBuilder()  
  107.                         .addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))  
  108.                         .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))  
  109.                         .build())  
  110.                 .setMessage(Message.newBuilder()  
  111.                         .setMsgContent(MSG_CONTENT)  
  112.                         .addExtra("from", "JPush")  
  113.                         .build())  
  114.                 .build();  
  115.     }  
  116. }  

以上是关于JPush极光推送Java服务器端实例的主要内容,如果未能解决你的问题,请参考以下文章

JPush极光推送Java服务器端实例

java SDK服务端推送 --极光推送(JPush)

JPush极光推送 Java调用服务器端API开发

AndroidStudio离线打包MUI集成JPush极光推送并在java后端管理推送

极光推送-java消息推送app

极光推送 JPush 简介 集成