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.导入依赖

 <!-- jpush -->
        <dependency>
            <groupId>cn.jpush.api</groupId>
            <artifactId>jpush-client</artifactId>
            <version>3.3.9</version>
        </dependency>

        <dependency>
            <groupId>cn.jpush.api</groupId>
            <artifactId>jiguang-common</artifactId>
            <version>1.0.3</version>
        </dependency>

2.极光推送工具类

1.一类

package com.zh.erp.framework.util.jpush;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.connection.NativeHttpClient;
import cn.jiguang.common.connection.NettyHttpClient;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jiguang.common.resp.ResponseWrapper;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.CIDResult;
import cn.jpush.api.push.GroupPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.*;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.*;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import io.netty.handler.codec.http.HttpMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;

public class PushExample {
    protected static final Logger LOG = LoggerFactory.getLogger(PushExample.class);

    // demo App defined in resources/jpush-api.conf 
    protected static final String APP_KEY1 = "274e2f473f13f6fa679368ae";
    protected static final String APP_KEY = "ebd355e590e6f7f93ba51477";
    protected static final String MASTER_SECRET1 = "896bb372344468fc0e3e47d4";
    protected static final String MASTER_SECRET = "2604f3b0706d46bd47ba919b";
    protected static final String GROUP_PUSH_KEY = "caff9bd51218a2def8d1a350";
    protected static final String GROUP_MASTER_SECRET = "06edba1d32ca66d9a54fd787";

    public static final String TITLE = "Test from API example";
    public static final String ALERT = "Test from API Example - alert";
    public static final String MSG_CONTENT = "Test from API Example - msgContent";
    public static final String REGISTRATION_ID = "0900e8d85ef";
    public static final String TAG = "tag_api";
    public static long sendCount = 0;
    private static long sendTotalTime = 0;

    public static void main(String[] args) {

        // 回调参数可参考下面方法
    //    testSendPushWithCustom();  //
   //     testSendPushWithCustomField();  //
//        testBatchSend();
     //   testSendPushWithCustomConfig();  //
        asynSendMessageWithCallback("user_1648_1062","您有一个新任务等待处理!","您有一个新任务等待处理!",
                "上海市浦东新区祝桥镇大沙路东海集贸市场","上海市浦东新区祝桥镇大沙路东海集贸市场","");
        //pushAline("user_1648_1062","您有一个新任务等待处理!","上海市浦东新区祝桥镇大沙路东海集贸市场");
//        testSendIosAlert();
//		testSendPush();
//        testGetCidList();
//        testSendPushes();
      //  testSendPush_fromJSON(); //
//        testSendPushWithCallback();
//		testSendPushWithCid();
    }

    // 使用 NettyHttpClient 异步接口发送请求
    public static void testSendPushWithCallback() {
        ClientConfig clientConfig = ClientConfig.getInstance();
        String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME);
        final NettyHttpClient client = new NettyHttpClient(ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET),
                null, clientConfig);
        try {
            URI uri = new URI(host + clientConfig.get(ClientConfig.PUSH_PATH));
            PushPayload payload = buildPushObject_all_alias_alert();
            client.sendRequest(HttpMethod.POST, payload.toString(), uri, new NettyHttpClient.BaseCallback() {
                @Override
                public void onSucceed(ResponseWrapper responseWrapper) {
                    LOG.info("Got result: " + responseWrapper.responseContent);
                }
            });
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    public static void testSendPush() {
        ClientConfig clientConfig = ClientConfig.getInstance();
        final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
//        String authCode = ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET);
        // Here you can use NativeHttpClient or NettyHttpClient or ApacheHttpClient.
        // Call setHttpClient to set httpClient,
        // If you don't invoke this method, default httpClient will use NativeHttpClient.

//        ApacheHttpClient httpClient = new ApacheHttpClient(authCode, null, clientConfig);
//        NettyHttpClient httpClient =new NettyHttpClient(authCode, null, clientConfig);
//        jpushClient.getPushClient().setHttpClient(httpClient);
        final PushPayload payload = buildPushObject_android_and_ios();
//        // For push, all you need do is to build PushPayload object.
//        PushPayload payload = buildPushObject_all_alias_alert();
        try {
            PushResult result = jpushClient.sendPush(payload);
            LOG.info("Got result - " + result);
            System.out.println(result);
            // 如果使用 NettyHttpClient,需要手动调用 close 方法退出进程
            // If uses NettyHttpClient, call close when finished sending request, otherwise process will not exit.
            // jpushClient.close();
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
            LOG.error("Sendno: " + payload.getSendno());

        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
            LOG.error("Sendno: " + payload.getSendno());
        }
    }

    public static void testSendPushWithEncrypt() {
        ClientConfig clientConfig = ClientConfig.getInstance();
        clientConfig.setEncryptType(EncryptKeys.ENCRYPT_SMS2_TYPE);
        final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
//        String authCode = ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET);
        // Here you can use NativeHttpClient or NettyHttpClient or ApacheHttpClient.
        // Call setHttpClient to set httpClient,
        // If you don't invoke this method, default httpClient will use NativeHttpClient.

//        ApacheHttpClient httpClient = new ApacheHttpClient(authCode, null, clientConfig);
//        NettyHttpClient httpClient =new NettyHttpClient(authCode, null, clientConfig);
//        jpushClient.getPushClient().setHttpClient(httpClient);
        final PushPayload payload = buildPushObject_android_and_ios();
//        // For push, all you need do is to build PushPayload object.
//        PushPayload payload = buildPushObject_all_alias_alert();
        try {
            PushResult result = jpushClient.sendPush(payload);
            LOG.info("Got result - " + result);
            System.out.println(result);
            // 如果使用 NettyHttpClient,需要手动调用 close 方法退出进程
            // If uses NettyHttpClient, call close when finished sending request, otherwise process will not exit.
            // jpushClient.close();
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
            LOG.error("Sendno: " + payload.getSendno());

        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
            LOG.error("Sendno: " + payload.getSendno());
        }
    }

    //use String to build PushPayload instance
    public static void testSendPush_fromJSON() {
        ClientConfig clientConfig = ClientConfig.getInstance();
        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(PlatformNotification.class, new InterfaceAdapter<PlatformNotification>())
                .create();
        // Since the type of DeviceType is enum, thus the value should be uppercase, same with the AudienceType.
        String payloadString = "{\"platform\":{\"all\":false,\"deviceTypes\":[\"IOS\"]},\"audience\":{\"all\":true,\"targets\":[{\"audienceType\":\"TAG_AND\",\"values\":[\"tag1\",\"tag_all\"]}]},\"notification\":{\"notifications\":[{\"soundDisabled\":false,\"badgeDisabled\":false,\"sound\":\"happy\",\"badge\":\"5\",\"contentAvailable\":false,\"alert\":\"Test from API Example - alert\",\"extras\":{\"from\":\"JPush\"},\"type\":\"cn.jpush.api.push.model.notification.IosNotification\"}]},\"message\":{\"msgContent\":\"Test from API Example - msgContent\"},\"options\":{\"sendno\":1429488213,\"overrideMsgId\":0,\"timeToLive\":-1,\"apnsProduction\":true,\"bigPushDuration\":0}}";
        PushPayload payload = gson.fromJson(payloadString, PushPayload.class);
        try {
            PushResult result = jpushClient.sendPush(payloadString);
            LOG.info("Got result - " + result);

        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
            // LOG.error("Sendno: " + payload.getSendno());

        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
            //LOG.error("Sendno: " + payload.getSendno());
        }
    }

    /**
     * 测试多线程发送 2000 条推送耗时
     */
    public static void testSendPushes() {
        ClientConfig clientConfig = ClientConfig.getInstance();
        final JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, clientConfig);
        String authCode = ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET);
        // Here you can use NativeHttpClient or NettyHttpClient or ApacheHttpClient.
        NativeHttpClient httpClient = new NativeHttpClient(authCode, null, clientConfig);
        // Call setHttpClient to set httpClient,
        // If you don't invoke this method, default httpClient will use NativeHttpClient.
//        ApacheHttpClient httpClient = new ApacheHttpClient(authCode, null, clientConfig);
        jpushClient.getPushClient().setHttpClient(httpClient);
        final PushPayload payload = buildPushObject_ios_tagAnd_alertWithExtrasAndMessage();
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread() {
                public void run() {
                    for (int j = 0; j < 200; j++) {
                        long start = System.currentTimeMillis();
                        try {
                            PushResult result = jpushClient.sendPush(payload);
                            LOG.info("Got result - " + result);

                        } catch (APIConnectionException e) {
                            LOG.error("Connection error. Should retry later. ", e);
                            LOG.error("Sendno: " + payload.getSendno());

                        } catch (APIRequestException e) {
                            LOG.error("Error response from JPush server. Should review and fix it. ", e);
                            LOG.info("HTTP Status: " + e.getStatus());
                            LOG.info("Error Code: " + e.getErrorCode());
                            LOG.info("Error Message: " + e.getErrorMessage());
                            LOG.info("Msg ID: " + e.getMsgId());
                            LOG.error("Sendno: " + payload.getSendno());
                        }

                        System.out.println("耗时" + (System.currentTimeMillis() - start) + "毫秒 sendCount:" + (++sendCount));
                    }
                }
            };
            thread.start();
        }
    }

    public void testSendGroupPush() {
        GroupPushClient groupPushClient = new GroupPushClient(GROUP_MASTER_SECRET, GROUP_PUSH_KEY);
        final PushPayload payload = buildPushObject_android_and_ios();
        try {
            Map<String, PushResult> result = groupPushClient.sendGroupPush(payload);
            for (Map.Entry<String, PushResult> entry : result.entrySet()) {
                PushResult pushResult = entry.getValue();
                PushResult.Error error = pushResult.error;
                if (error != null) {
                    LOG.info("AppKey: " + entry.getKey() + " error code : " + error.getCode() + " error message: " + error.getMessage());
                } else {
                    LOG.info("AppKey: " + entry.getKey() + " sendno: " + pushResult.sendno + " msg_id:" + pushResult.msg_id);
                }

            }
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
            LOG.error("Sendno: " + payload.getSendno());

        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
            LOG.error("Sendno: " + payload.getSendno());
        }
    }

    public static PushPayload buildPushObject_all_all_alert() {
        return PushPayload.alertAll(ALERT);
    }

    public static PushPayload buildPushObject_all_alias_alert() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.alias("alias1"))
                .setNotification(Notification.alert(ALERT))
                .build();
    }

    public static PushPayload buildPushObject_android_tag_alertWithTitle() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.tag("tag1"))
                .setNotification(Notification.android(ALERT, TITLE, null))
                .build();
    }

    public static PushPayload buildPushObject_android_and_ios() {
        Map<String, String> extras = new HashMap<String, String>();
        extras.put("test", "https://community.jiguang.cn/push");
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.all())
                .setNotification(Notification.newBuilder()
                        .setAlert("alert content")
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setTitle("Android Title")
                                .addExtras(extras).build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .incrBadge(1)
                                .addExtra("extra_key", "extra_value").build())
                        .build())
                .build();
    }

    public static void buildPushObject_with_extra() {

        JsonObject jsonExtra = new JsonObject();
        jsonExtra.addProperty("extra1", 1);
        jsonExtra.addProperty("extra2", false);

        Map<String, String> extras = new HashMap<String, String>();
        extras.put("extra_1", "val1");
        extras.put("extra_2", "val2");

        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.tag("tag1"))
                .setNotification(Notification.newBuilder()
                        .setAlert("alert content")
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setTitle("Android Title")
                                .addExtras(extras)
                                .addExtra("booleanExtra", false)
                                .addExtra("numberExtra", 1)
                                .addExtra("jsonExtra", jsonExtra)
                                .build())
                        .addPlatformNotification(IosNotification.newBuilder()
                                .incrBadge(1)
                                .addExtra("extra_key", "extra_value").build())
                        .build())
                .build();

        System.out.println(payload.toJSON());
    }

    public static PushPayload buildPushObject_ios_tagAnd_alertWithExtrasAndMessage() {
        JsonObject sound = new JsonObject();
        sound.add("critical", new JsonPrimitive(1));
        sound.add("name", new JsonPrimitive("default"));
        sound.add("volume", new JsonPrimitive(0.2));
        return PushPayload.newBuilder()
                .setPlatform(Platform.ios())
                .setAudience(Audience.tag_and("tag1", "tag_all"))
                .setNotification(Notification.newBuilder()
                        .addPlatformNotification(IosNotification.newBuilder()
                                .setAlert(ALERT)
                                .setBadge(5)
                                .setMutableContent(false)
//                                .setSound("happy")
                                .setSound(sound)
                                .addExtra("from", "JPush")
                                .build())
                        .build())
                .setMessage(Message.content(MSG_CONTENT))
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .build())
                .build();
    }

    public static PushPayload buildPushObject_android_newly_support() {

        JsonObject inbox = new JsonObject();
        inbox.add("line1", new JsonPrimitive("line1 string"));
        inbox.add("line2", new JsonPrimitive("line2 string"));
        inbox.add("contentTitle", new JsonPrimitive("title string"));
        inbox.add("summaryText", new JsonPrimitive("+3 more"));

        JsonObject intent = new JsonObject();
        intent.add("url", new JsonPrimitive("intent:#Intent;component=com.jiguang.push/com.example.jpushdemo.SettingActivity;end"));

        Notification notification = Notification.newBuilder()
                .addPlatformNotification(AndroidNotification.newBuilder()
                        .setAlert(ALERT)
                        .setBigPicPath("path to big picture")
                        .setBigText("long text")
                        .setBuilderId(1)
                        .setCategory("CATEGORY_SOCIAL")
                        .setInbox(inbox)
                        .setStyle(1)
                        .setTitle("Alert test")
                        .setPriority(1)
                        .setLargeIcon("http://www.jiguang.cn/largeIcon.jpg")
                        .setIntent(intent)
                        .build())
                .build();
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.all())
                .setNotification(notification)
                .setOptions(Options.newBuilder()
                        .setApnsProduction(true)
                        .setSendno(ServiceHelper.generateSendno())
                        .build())
                .build();
    }

    public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios())
                .setAudience(Audience.newBuilder()
                        .addAudienceTarget(AudienceTarget.tag("tag1", "tag2"))
                        .addAudienceTarget(AudienceTarget.alias("alias1", "alias2"))
                        .build())
                .setMessage(Message.newBuilder()
                        .setMsgContent(MSG_CONTENT)
                        .addExtra("from", "JPush")
                        .build())
                .build();
    }

    public static PushPayload buildPushObject_all_tag_not() {
        return PushPayload.newBuilder()
                .setPlatform(Platform.all())
                .setAudience(Audience.tag_not("abc", "123"))
                .setNotification(Notification.alert(ALERT))
                .build();
    }

    public static PushPayload buildPushObject_android_cid() {
        Collection<String> list = new LinkedList<String>();
        list.add("1507bfd3f79558957de");
        list.add("1507bfd3f79554957de");
        list.add("1507bfd3f79555957de");
        list.add("1507bfd3f79556957de");
        list.add("1507ffd3f79545957de");
        list.add("1507ffd3f79457957de");
        list.add("1507ffd3f79456757de");


        return PushPayload.newBuilder()
                .setPlatform(Platform.android())
//                .setAudience(Audience.registrationId("1507bfd3f79558957de"))
                .setAudience(Audience.registrationId(list))
                .setNotification(Notification.alert(ALERT))
                .setCid("cid")
                .build();
    }

    public static void testSendPushWithCustomConfig() {
        ClientConfig config = ClientConfig.getInstance();
        // Setup the custom hostname
        config.setPushHostName("https://api.jpush.cn");

        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, config);

        // For push, all you need do is to build PushPayload object.
        PushPayload payload = buildPushObject_all_all_alert();

        try {
            PushResult result = jpushClient.sendPush(payload);
            LOG.info("Got result - " + result);

        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);

        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
        }
    }

    public static void testSendIosAlert() {
        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY);

        IosAlert alert = IosAlert.newBuilder()
                .setTitleAndBody("test alert", "subtitle", "test ios alert json")
                .setActionLocKey("PLAY")
                .build();
        try {
            PushResult result = jpushClient.sendIosNotificationWithAlias(alert, new HashMap<String, String>(), "alias1");
            LOG.info("Got result - " + result);
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
        }
    }

    public static void testSendWithSMS() {
        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY);
        try {
//            SMS sms = SMS.content(1, 10);
            SMS sms = SMS.newBuilder()
                    .setDelayTime(1000)
                    .setTempID(2000)
                    .addPara("Test", 1)
                    .build();
            PushResult result = jpushClient.sendAndroidMessageWithAlias("Test SMS", "test sms", sms, "alias1");
            LOG.info("Got result - " + result);
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
        }
    }

    public static void testGetCidList() {
        JPushClient jPushClient = new JPushClient(MASTER_SECRET, APP_KEY);
        try {
            CIDResult result = jPushClient.getCidList(3, "push");
            LOG.info("Got result - " + result);
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
        }
    }

    public static void testSendPushWithCid() {
        JPushClient jPushClient = new JPushClient(MASTER_SECRET, APP_KEY);
        PushPayload pushPayload = buildPushObject_android_cid();
        try {
            PushResult result = jPushClient.sendPush(pushPayload);
            LOG.info("Got result - " + result);
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
        }
    }

    /**
     * 批量单推接口
     * https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/#vip
     */
    public static void testBatchSend() {

        JPushClient jPushClient = new JPushClient(MASTER_SECRET, APP_KEY);
        try {
            {
                List<PushPayload> pushPayloadList = new ArrayList<>();
                PushPayload.Builder builder1 = PushPayload.newBuilder();
                builder1.setMessage(Message.content("content1 by alias"))
                        .setNotification(Notification.alert(ALERT))
                        .setPlatform(Platform.all())
                        .setAudience(Audience.all())
                        .setOptions(Options.sendno())
                        .setTarget("1507ffd3f79456757de");
                pushPayloadList.add(builder1.build());

                PushPayload.Builder builder2 = PushPayload.newBuilder();
                builder2.setMessage(Message.content("content2 by alias"))
                        .setNotification(Notification.alert(ALERT))
                        .setPlatform(Platform.android())
                        .setAudience(Audience.all())
                        .setOptions(Options.sendno())
                        .setTarget("1507ffd3f79456757de");
                pushPayloadList.add(builder2.build());

                BatchPushResult result = jPushClient.batchSendPushByAlias(pushPayloadList);
                LOG.info("batchSendPushByAlias param: {}, result: {}", pushPayloadList, new Gson().toJson(result.getBatchPushResult()));
            }

            {
                List<PushPayload> pushPayloadList = new ArrayList<>();
                PushPayload.Builder builder1 = PushPayload.newBuilder();
                builder1.setMessage(Message.content("content1 by regId"))
                        .setNotification(Notification.alert(ALERT))
                        .setPlatform(Platform.android())
                        .setAudience(Audience.all())
                        .setOptions(Options.sendno())
                        .setTarget("1507ffd3f79456757de");
                pushPayloadList.add(builder1.build());

                PushPayload.Builder builder2 = PushPayload.newBuilder();
                builder2.setMessage(Message.content("content2 by regId"))
                        .setNotification(Notification.alert(ALERT))
                        .setAudience(Audience.all())
                        .setPlatform(Platform.ios())
                        .setOptions(Options.sendno())
                        .setTarget("1507ffd3f79456757de");
                pushPayloadList.add(builder2.build());

                BatchPushResult result = jPushClient.batchSendPushByRegId(pushPayloadList);
                LOG.info("batchSendPushByRegId param: {}, result: {}", pushPayloadList, new Gson().toJson(result.getBatchPushResult()));
            }

        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
        }
    }

    /**
     * 自定义发送参数名称, 华为客户可参考该方法
     */
    public static void testSendPushWithCustomField() {

        ClientConfig config = ClientConfig.getInstance();
        // Setup the custom hostname
        config.setPushHostName("https://api.jpush.cn");

        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, config);

        Notification notification = Notification.newBuilder()
                .addPlatformNotification(AndroidNotification.newBuilder()
                        .setAlert(ALERT)
                        .setTitle("Alert test")
                        .setLargeIcon("http://www.jiguang.cn/largeIcon.jpg")
                        .addCustom("uri_activity", "uri_activity")
                        .addCustom("uri_flag", "uri_flag")
                        .addCustom("uri_action", "uri_action")
                        .build())
                .build();

        PushPayload.Builder payloadBuilder = new PushPayload.Builder()
                .setPlatform(Platform.all())
                .setAudience(Audience.all())
                .setNotification(notification);

        try {
            PushResult result = jpushClient.sendPush(payloadBuilder.build());
            LOG.info("Got result - " + result);

        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);

        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
        }
    }

    /**
     * 回调参数示例
     */
    public static void testSendPushWithCustom() {

        ClientConfig config = ClientConfig.getInstance();
        // Setup the custom hostname
        config.setPushHostName("https://api.jpush.cn");

        JPushClient jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, config);

        Notification notification = Notification.newBuilder()
                .addPlatformNotification(AndroidNotification.newBuilder()
                        .setAlert(ALERT)
                        .setTitle("Alert test")
                        .build())
                .build();

        JsonObject callback = new JsonObject();
        callback.addProperty("url", "https://www.jiguagn.cn/callback");
        JsonObject params = new JsonObject();
        params.addProperty("name", "joe");
        params.addProperty("age", 26);
        callback.add("params", params);
        callback.addProperty("type", 3);

        PushPayload.Builder payloadBuilder = new PushPayload.Builder()
                .setPlatform(Platform.all())
                .setAudience(Audience.all())
                .setNotification(notification)
                .addCustom("callback", callback);

        try {
            PushResult result = jpushClient.sendPush(payloadBuilder.build());
            LOG.info("Got result - " + result);
        } catch (APIConnectionException e) {
            LOG.error("Connection error. Should retry later. ", e);
        } catch (APIRequestException e) {
            LOG.error("Error response from JPush server. Should review and fix it. ", e);
            LOG.info("HTTP Status: " + e.getStatus());
            LOG.info("Error Code: " + e.getErrorCode());
            LOG.info("Error Message: " + e.getErrorMessage());
            LOG.info("Msg ID: " + e.getMsgId());
        }
    }

    public static void asynSendMessageWithCallback(String alias, String notification_title, String msg_title, String msg_content, String extrasparam, String content_type) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME);
        System.out.println(APP_KEY+"***"+MASTER_SECRET+";"+APP_KEY1+"***"+MASTER_SECRET1);
        final NettyHttpClient client = new NettyHttpClient(ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET),
                null, clientConfig);
        final NettyHttpClient client1 = new NettyHttpClient(ServiceHelper.getBasicAuthorization(APP_KEY1, MASTER_SECRET1),
                null, clientConfig);
        try {
            URI uri = new URI(host + clientConfig.get(ClientConfig.PUSH_PATH));
            PushPayload payload = buildPushObject_android_alias_alertWithTitle(alias, notification_title, msg_title, msg_content, extrasparam, content_type);
            System.out.println("payload="+payload+";uri="+uri);
            client.sendRequest(HttpMethod.POST, payload.toString(), uri, new NettyHttpClient.BaseCallback() {
                @Override
                public void onSucceed(ResponseWrapper responseWrapper) {
                    LOG.info("Got result: " + responseWrapper.responseContent);
                    System.out.println("Got result: " + responseWrapper.responseContent);
                }
            });
            client1.sendRequest(HttpMethod.POST, payload.toString(), uri, new NettyHttpClient.BaseCallback() {
                @Override
                public void onSucceed(ResponseWrapper responseWrapper) {
                    LOG.info("Got result1: " + responseWrapper.responseContent);
                    System.out.println("Got result1: " + responseWrapper.responseContent);
                }
            });
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    private static PushPayload buildPushObject_android_alias_alertWithTitle(String alias, String notification_title, String msg_title, String msg_content, String extrasparam, String content_type) {
        return PushPayload.newBuilder()
                //指定要推送的平台,all代表当前应用配置了的所有平台,也可以传android等具体平台
                .setPlatform(Platform.android())
                //指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
                .setAudience(Audience.alias(alias))
                //.setAudience(Audience.all())
                //jpush的通知,android的由jpush直接下发,iOS的由apns服务器下发,Winphone的由mpns下发
                .setNotification(Notification.newBuilder()
                        //指定当前推送的android通知
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(msg_content)
                                .setTitle(notification_title)
                                //此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
                                .addExtra("data", extrasparam)
                                .build())
                        .build()
                )
                //Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
                // sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
                // [通知与自定义消息有什么区别?]了解通知和自定义消息的区别
                .setMessage(Message.newBuilder()
                        .setMsgContent(msg_content)
                        .setTitle(msg_title)
                        .setContentType(content_type)
                        .addExtra("data", extrasparam)
                        .build())
                .setOptions(Options.newBuilder()
                        //此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
                        .setApnsProduction(true)
                        //此字段是给开发者自己给推送编号,方便推送者分辨推送记录
                        .setSendno(1)
                        //此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天,单位为秒
                        .setTimeToLive(86400)
                        .build())
                .build();
    }

    public static void asynSendMessageWithCallbackAll(String tag, String notification_title, String msg_title, String msg_content, String extrasparam, String content_type) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME);
        final NettyHttpClient client = new NettyHttpClient(ServiceHelper.getBasicAuthorization(APP_KEY, MASTER_SECRET),
                null, clientConfig);
        try {
            URI uri = new URI(host + clientConfig.get(ClientConfig.PUSH_PATH));
            PushPayload payload = buildPushObject_android_alias_alertWithTitleAll(tag, notification_title, msg_title, msg_content, extrasparam, content_type);
            client.sendRequest(HttpMethod.POST, payload.toString(), uri, new NettyHttpClient.BaseCallback() {
                @Override
                public void onSucceed(ResponseWrapper responseWrapper) {
                    LOG.info("Got result: " + responseWrapper.responseContent);
                }
            });
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    private static PushPayload buildPushObject_android_alias_alertWithTitleAll(String tag, String notification_title, String msg_title, String msg_content, String extrasparam, String content_type) {
        return PushPayload.newBuilder()
                //指定要推送的平台,all代表当前应用配置了的所有平台,也可以传android等具体平台
                .setPlatform(Platform.android())
                //指定推送的接收对象,all代表所有人,也可以指定已经设置成功的tag或alias或该应应用客户端调用接口获取到的registration id
                .setAudience(Audience.tag(tag))
                //jpush的通知,android的由jpush直接下发,iOS的由apns服务器下发,Winphone的由mpns下发
                .setNotification(Notification.newBuilder()
                        //指定当前推送的android通知
                        .addPlatformNotification(AndroidNotification.newBuilder()
                                .setAlert(msg_content)
                                .setTitle(notification_title)
                                //此字段为透传字段,不会显示在通知栏。用户可以通过此字段来做一些定制需求,如特定的key传要指定跳转的页面(value)
                                .addExtra("data", extrasparam)
                                .build())
                        .build()
                )
                //Platform指定了哪些平台就会像指定平台中符合推送条件的设备进行推送。 jpush的自定义消息,
                // sdk默认不做任何处理,不会有通知提示。建议看文档http://docs.jpush.io/guideline/faq/的
                // [通知与自定义消息有什么区别?]了解通知和自定义消息的区别
                .setMessage(Message.newBuilder()
                        .setMsgContent(msg_content)
                        .setTitle(msg_title)
                        .setContentType(content_type)
                        .addExtra("data", extrasparam)
                        .build())
                .setOptions(Options.newBuilder()
                        //此字段的值是用来指定本推送要推送的apns环境,false表示开发,true表示生产;对android和自定义消息无意义
                        .setApnsProduction(true)
                        //此字段是给开发者自己给推送编号,方便推送者分辨推送记录
                        .setSendno(1)
                        //此字段的值是用来指定本推送的离线保存时长,如果不传此字段则默认保存一天,最多指定保留十天,单位为秒
                        .setTimeToLive(86400)
                        .build())
                .build();
    }

    public static void pushAline(String tag, String notification_title, String msg_content){
        ClientConfig config = ClientConfig.getInstance();
        JPushClient client = new JPushClient(MASTER_SECRET, APP_KEY, null, config);
        PushPayload payload = PushPayload.newBuilder()
                .setPlatform(Platform.android())//推送平台
                .setAudience(Audience.alias(tag))//推送目标
                .setNotification(Notification.newBuilder().addPlatformNotification(AndroidNotification.newBuilder()
                        .setAlert(msg_content)
                        .setTitle(notification_title).build()).build())//通知消息(标题,内容)
                .setOptions(Options.newBuilder().setApnsProduction(true).setTimeToLive(86400).build()//离线消息保存时间
                )
                .build();
        try {
            PushResult result = client.sendPush(payload);//推送
            System.out.println("推送结果:" + result.getResponseCode());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

2.二类


 
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import com.erenju.util.GlobleConfig;    
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xhgx.domain.RestInfo;
import com.xhgx.web.util.JSONObject;

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

3.三类

#极光推送参数设定    yml
jpush: 
  appkey: 
  masterSecret: 
  #离线保存时间 7天 最长10天
  liveTime: 604800
  #推送开关
  enable: true
@Component  //配置类
@ConfigurationProperties(prefix="jpush")
public class JPushConfig {

    public static String APP_KEY;

    public static String MASTER_SECRET;

    public static long LIVE_TIME;

    /**
     *  是否开启推送
     */
    public static Boolean ENABLE;

    public void setAppKey(String appKey) {
        JPushConfig.APP_KEY = appKey;
    }

    public void setMasterSecret(String masterSecret) {
        JPushConfig.MASTER_SECRET = masterSecret;
    }

    public void setLiveTime(long liveTime) {
        JPushConfig.LIVE_TIME = liveTime;
    }

    public void setEnable(Boolean enable) {
        JPushConfig.ENABLE = enable;
    }
public class JPushUtil {

    private static final Logger logger = LoggerFactory.getLogger(JPushUtil.class);

    /**
     * 消息自定义即时推送
     * @param jPushMsgVO
     * @return
     */
    public static PushLog messageCustomPush(JPushMsgVO jPushMsgVO) {
        JPushClient jpushClient = buildJPushClient(jPushMsgVO.getLiveTime());
        PushPayload payload = buildMessageCustomPushPayload(jPushMsgVO.getTitle(), jPushMsgVO.getContent(), jPushMsgVO.getExtrasMap(), jPushMsgVO.getPlatform(), jPushMsgVO.getPushType(), jPushMsgVO.getPushObject());
        PushResult result = null;
        PushLog pushLog = BeanUtils.copyResult(jPushMsgVO, PushLog::new);
        pushLog.setCreateTime(new Date());
        pushLog.setPushSort(PushSortEnum.MESSAGE.getCode());
        try {
            result = jpushClient.sendPush(payload);
            pushLog.setMsgId(String.valueOf(result.msg_id));
            logger.info("极光推送条件{},结果{}", payload,result);
        } catch (APIConnectionException e) {
            logger.error("极光推送连接错误,请稍后重试 ", e);
            logger.error("SendNo: " + payload.getSendno());
        } catch (APIRequestException e) {
            logger.error("极光服务器响应出错,请修复! ", e);
            logger.info("HTTP Status: {}", e.getStatus());
            logger.info("Error Code: {}", e.getErrorCode());
            logger.info("Error Message: {}", e.getErrorMessage());
            logger.error("SendNo: {}", payload.getSendno());
            pushLog.setMsgId(String.valueOf(e.getMsgId()));
            pushLog.setStatusCode(e.getErrorCode());
            pushLog.setErrMsg(e.getErrorMessage());
        } finally {
            pushLog.setPayload(payload.toString());
            pushLog.setSendNo(payload.getSendno());
            pushLog.setPushTime(new Date());
        }
        return pushLog;
    }

    /**
     * 消息自定义定时推送
     * @param jPushMsgVO
     * @return
     */
    public static PushLog messageCustomSchedulePush(JPushMsgVO jPushMsgVO) {
        JPushClient jpushClient = buildJPushClient(jPushMsgVO.getLiveTime());
        PushPayload payload = buildMessageCustomPushPayload(jPushMsgVO.getTitle(), jPushMsgVO.getContent(), jPushMsgVO.getExtrasMap(), jPushMsgVO.getPlatform(), jPushMsgVO.getPushType(), jPushMsgVO.getPushObject());
        ScheduleResult result = null;
        PushLog pushLog = BeanUtils.copyResult(jPushMsgVO, PushLog::new);
        pushLog.setCreateTime(new Date());
        pushLog.setStatusCode(-1);
        try {
            result = jpushClient.createSingleSchedule("CustomScheduleJPush", jPushMsgVO.getPushTime().toString(), payload);
            pushLog.setMsgId(result.getSchedule_id());
            logger.info("极光推送条件{},结果{}", payload,result);
        } catch (APIConnectionException e) {
            logger.error("极光推送连接错误,请稍后重试 ", e);
            logger.error("SendNo: " + payload.getSendno());
        } catch (APIRequestException e) {
            logger.error("极光服务器响应出错,请修复! ", e);
            logger.info("HTTP Status: {}", e.getStatus());
            logger.info("Error Code: {}", e.getErrorCode());
            logger.info("Error Message: {}", e.getErrorMessage());
            logger.error("SendNo: {}", payload.getSendno());
            pushLog.setStatusCode(e.getErrorCode());
            pushLog.setErrMsg(e.getErrorMessage());
        } finally {
            pushLog.setPayload(payload.toString());
            pushLog.setSendNo(payload.getSendno());
            pushLog.setPushTime(new Date());
        }
        return pushLog;
    }

    /**
     * 通知自定义即时推送
     * @param jPushMsgVO
     * @return 推送记录
     */
    public static PushLog notifyCustomPush(JPushMsgVO jPushMsgVO) {
        JPushClient jpushClient = buildJPushClient(jPushMsgVO.getLiveTime());
        //构造推送条件
        PushPayload payload = buildNotifyCustomPushPayload(jPushMsgVO.getTitle(), jPushMsgVO.getContent(), jPushMsgVO.getExtrasMap(), jPushMsgVO.getPlatform(), jPushMsgVO.getPushType(), jPushMsgVO.getPushObject());

        PushResult result = null;
        PushLog pushLog = BeanUtils.copyResult(jPushMsgVO, PushLog::new);
        pushLog.setCreateTime(new Date());
        pushLog.setStatusCode(-1);

        try {
            result = jpushClient.sendPush(payload);
            pushLog.setMsgId(String.valueOf(result.msg_id));
            pushLog.setPushMethod(PushMethodEnum.IMMEDIATE.getCode());
            pushLog.setStatusCode(result.statusCode);
            if(result.statusCode != 0){
                pushLog.setErrMsg(result.error.getMessage());
            }
            pushLog.setPayload(payload.toString());
            pushLog.setSendNo(payload.getSendno());
            logger.info("极光推送条件{},结果{}", payload,result);
        } catch (APIConnectionException e) {
            logger.error("极光推送连接错误,请稍后重试 ", e);
            logger.error("SendNo: " + payload.getSendno());
        } catch (APIRequestException e) {
            logger.error("极光服务器响应出错,请修复!", e);
            logger.info("HTTP Status: {}", e.getStatus());
            logger.info("Error Code: {}", e.getErrorCode());
            logger.info("Error Message: {}", e.getErrorMessage());
            logger.error("SendNo: {}", payload.getSendno());
        } finally {

            pushLog.setPushTime(new Date());
        }
        return pushLog;
    }

    /**
     * 通知自定义定时推送
     * @param jPushMsgVO
     * @return
     */
    public static PushLog notifyCustomSchedulePush(JPushMsgVO jPushMsgVO) {
        JPushClient jpushClient = buildJPushClient(jPushMsgVO.getLiveTime());
        PushPayload payload = buildNotifyCustomPushPayload(jPushMsgVO.getTitle(), jPushMsgVO.getContent(), jPushMsgVO.getExtrasMap(), jPushMsgVO.getPlatform(), jPushMsgVO.getPushType(), jPushMsgVO.getPushObject());
        ScheduleResult result = null;
        PushLog pushLog = new PushLog();
        pushLog.setPushMethod(PushMethodEnum.TIMING.getCode());
        pushLog.setCreateTime(new Date());
        pushLog.setStatusCode(-1);
        try {
            result = jpushClient.createSingleSchedule("CustomScheduleJPush", jPushMsgVO.getPushTime().toString(), payload);
            pushLog.setMsgId(result.getSchedule_id());
            pushLog.setPayload(payload.toString());
            pushLog.setSendNo(payload.getSendno());
            logger.info("极光推送条件{},结果{}", payload,result);
        } catch (APIConnectionException e) {
            logger.error("极光推送连接错误,请稍后重试 ", e);
            logger.error("SendNo: " + payload.getSendno());
        } catch (APIRequestException e) {
            logger.error("极光服务器响应出错,请修复! ", e);
            logger.info("HTTP Status: {}", e.getStatus());
            logger.info("Error Code: {}", e.getErrorCode());
            logger.info("Error Message: {}", e.getErrorMessage());
            logger.error("SendNo: {}", payload.getSendno());
            pushLog.setStatusCode(e.getErrorCode());
            pushLog.setErrMsg(e.getErrorMessage());
        } finally {
            pushLog.setPushTime(new Date());
        }
        return pushLog;
    }

    /**
     * 取消定时推送
     */
    public static boolean deleteSchedule(String scheduleId) {
        boolean result;
        try {
            JPushClient jPushClient = new JPushClient(JPushConfig.MASTER_SECRET, JPushConfig.APP_KEY);
            jPushClient.deleteSchedule(scheduleId);
            result = true;
        } catch (APIConnectionException e) {
            logger.error("Connection error. Should retry later. ", e);
            result = false;
        } catch (APIRequestException e) {
            logger.error("Error response from JPush server. Should review and fix it. ", e);
            logger.info("HTTP Status: {}", e.getStatus());
            logger.info("Error Code: {}", e.getErrorCode());
            logger.info("Error Message: {}", e.getErrorMessage());
            result = false;
        }
        return result;
    }

    /**
     * 构建自定义消息的推送消息对象
     *
     * @param title       推送消息标题
     * @param content     推送消息内容(为了单行显示全,尽量保持在22个汉字以下)
     * @param extrasMap   额外推送信息(不会显示在通知栏,传递数据用)
     * @param platform    推送的设备类型,默认全部类型
     * @param pushTypeEnum    推送方式,默认广播推送
     * @param pushObject PushTypeEnum为广播推送:此字段无意义;PushTypeEnum为别名推送:此字段为推送指定的别名;PushTypeEnum为标签推送:此字段为推送指定的标签
     * @return 推送消息对象
     */
    private static PushPayload buildMessageCustomPushPayload(String title, String content, Map<String, String> extrasMap, PushPlatformEnum platform, PushTypeEnum pushTypeEnum, List<String> pushObject) {
        // 批量删除数组中空元素
        return PushPayload.newBuilder()
                // 设置推送的设备类型
                .setPlatform(null == platform ? Platform.all() : getPlatform(platform))
                // 设置推送的受众
                .setAudience(getAudience(pushTypeEnum, pushObject))
                // 设置推送标题、内容、额外信息
                .setMessage(Message.newBuilder().setTitle(title).setMsgContent(content).addExtras(null == extrasMap ? new HashMap<>() : extrasMap).build())
                .build();
    }

    /**
     * 构建自定义的通知推送对象
     *
     * @param title       推送通知标题
     * @param content     推送通知内容(为了单行显示全,尽量保持在22个汉字以下)
     * @param extrasMap   额外推送信息(不会显示在通知栏,传递数据用)
     * @param platform    推送的设备类型,默认全部类型
     * @param PushTypeEnum    推送方式,默认广播推送
     * @param pushObject PushTypeEnum为广播推送:此字段无意义;PushTypeEnum为别名推送:此字段为推送指定的别名;PushTypeEnum为标签推送:此字段为推送指定的标签
     * @return 推送通知对象
     */
    private static PushPayload buildNotifyCustomPushPayload(String title, String content, Map<String, String> extrasMap, PushPlatformEnum platform, PushTypeEnum PushTypeEnum, List<String> pushObject) {
        extrasMap = extrasMap == null ? new HashMap<>() : extrasMap;
        return PushPayload.newBuilder().setPlatform(null == platform ? Platform.all() : getPlatform(platform))
                .setAudience(getAudience(PushTypeEnum, pushObject))
                .setNotification(Notification.newBuilder().setAlert(content)
                        .addPlatformNotification(AndroidNotification.newBuilder().setTitle(title).addExtras(extrasMap).build())
                        .addPlatformNotification(IosNotification.newBuilder().incrBadge(1).addExtras(extrasMap).build())
                        .build())
                .build();
    }

    /**
     * 构建推送客户端
     */
    private static JPushClient buildJPushClient(Long liveTime) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        clientConfig.setTimeToLive(liveTime == null ? JPushConfig.LIVE_TIME : liveTime);
        return new JPushClient(JPushConfig.MASTER_SECRET, JPushConfig.APP_KEY, null, clientConfig);
    }

    /**
     * 查询记录推送成功条数(暂未使用)
     *
     * @param msg_id 在推送返回结果PushResult中保存
     */
    public void countPush(String msg_id) {
        JPushClient jpushClient = new JPushClient(JPushConfig.MASTER_SECRET, JPushConfig.APP_KEY);
        try {
            ReceivedsResult result = jpushClient.getReportReceiveds(msg_id);
            ReceivedsResult.Received received = result.received_list.get(0);
            logger.debug("Android接受信息:" + received.android_received + "\n IOS端接受信息:" + received.ios_apns_sent);
            logger.debug("极光推送返回结果 - " + result);
        } catch (APIConnectionException e) {
            logger.error("极光推送连接错误,请稍后重试", e);
        } catch (APIRequestException e) {
            logger.error("检查错误,并修复推送请求", e);
            logger.info("HTTP Status: " + e.getStatus());
            logger.info("Error Code: " + e.getErrorCode());
            logger.info("Error Message: " + e.getErrorMessage());
        }
    }

    /**
     * 异步请求推送方式,使用NettyHttpClient,异步接口发送请求,通过回调函数可以获取推送成功与否情况
     */
    public void sendPushWithCallback(String title, String content, Map<String, String> extrasMap, PushPlatformEnum platform, PushTypeEnum PushTypeEnum, List<String> pushObject) {
        ClientConfig clientConfig = ClientConfig.getInstance();
        clientConfig.setTimeToLive(JPushConfig.LIVE_TIME);
        String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME);
        NettyHttpClient client = new NettyHttpClient(
                ServiceHelper.getBasicAuthorization(JPushConfig.APP_KEY, JPushConfig.MASTER_SECRET), null, clientConfig);
        try {
            URI uri = new URI(host + clientConfig.get(ClientConfig.PUSH_PATH));
            PushPayload payload = buildNotifyCustomPushPayload(title, content, extrasMap, platform, PushTypeEnum, pushObject);
            client.sendRequest(HttpMethod.POST, payload.toString(), uri, responseWrapper -> {
                if (200 == responseWrapper.responseCode) {
                    logger.info("极光推送成功");
                } else {
                    logger.info("极光推送失败,返回结果: " + responseWrapper.responseContent);
                }
            });
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } finally {
            // 需要手动关闭Netty请求进程,否则会一直保留
            client.close();
        }

    }

    /**
     * 根据推送类型获取推送的受众
     */
    private static Audience getAudience(PushTypeEnum pushTypeEnum, List<String> pushObject) {
        switch (pushTypeEnum){
            // 别名推送
            case ALIAS:
                return Audience.alias(filterEmptyAndRepeatElement(pushObject));
            // 标签推送
            case TAG:
                return Audience.tag(filterEmptyAndRepeatElement(pushObject));
            //注册ID
            case REGISTRATION_ID:
                return Audience.registrationId(filterEmptyAndRepeatElement(pushObject));
            // 广播推送
            default:
                return Audience.all();
        }
    }

    /**
     * 过滤 空元素(需删除如:null,""," ")和重复的元素
     */
    private static List<String> filterEmptyAndRepeatElement(List<String> stringList) {
        return stringList.stream().filter(item -> item != null && !"".equals(item)).distinct().collect(Collectors.toList());
    }

    private static Platform getPlatform(PushPlatformEnum pushPlatformEnum){
        switch (pushPlatformEnum){
            case ALL:
                return Platform.all();
            case ANDROID:
                return Platform.android();
            case IOS:
                return Platform.ios();
            default:
                return Platform.android_ios();
        }
    }
}

Java中的WebSocket是一种网络通信协议,它提供了服务器和客户端之间全双工(双向)的通信能力。使用WebSocket协议,服务端可以实时地向客户端推送消息,而不需要客户端先发起请求。这使得它可以用于实现实时应用,如聊天系统、在线游戏、实时监控等。 在Java中,使用WebSocket服务端消息实时推送通常涉及到以下几个步骤: 1. 创建WebSocket服务器:可以使用Java EE的Servlet API,或者使用更高级的库如Spring Framework的Spring WebSocket。 2. 定义WebSocket端点:这通常是通过注解`@ServerEndpoint`来实现的,在这个端点上定义了客户端连接、消息接收、消息发送和会话关闭等事件的处理方法。 3. 管理连接会话:每个WebSocket连接都是一个会话,服务器端可以通过会话对象向客户端发送消息。 4. 消息推送:通过会话对象的`sendMessage`方法,可以将消息实时推送给客户端。 下面是一个简单的示例代码,展示了如何在Java中使用WebSocket进行消息推送: ```java import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.concurrent.CopyOnWriteArraySet; @ServerEndpoint("/websocket") public class WebSocketServer { private static final Set<Session> sessions = new CopyOnWriteArraySet<>(); @OnOpen public void onOpen(Session session) { sessions.add(session); System.out.println("新连接:" + session.getId()); } public void sendMessage(String message) { for (Session session : sessions) { try { if (session.isOpen()) { session.getBasicRemote().sendText(message); } } catch (IOException e) { e.printStackTrace(); } } } } ``` 在这个例子中,`@ServerEndpoint("/websocket")`标记了WebSocket服务端点,当客户端连接时,`onOpen`方法会被调用,并将新的会话加入会话集合中。`sendMessage`方法则用于向所有连接的客户端推送消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值