Teach you step by step how to push Aurora

Aurora push, in fact, rely on a third party platform push messaging, push multiport match, you can support the device has Android, ios, winphone, alone still can not say that we know what he can do, let's look at a small example.

First, the first register aurora service account, log into the application settings, record AppKey and Master Secret, java developers to use the background.

Second, click on the "Push Settings":
Set Android and iOS:
Android application package name their own definition, download the demo, Android Developer View Integration Guide, the sdk integrated into the project.
Here Insert Picture Description
iOS application package name their own definition, download the demo, iOS Developer View Integration Guide, sdk will be integrated into the project.
Here Insert Picture Description
Three, Android and iOS call back interfaces are provided within the java own business: Aurora user id and binding interface.
After successfully sending the binding notice, send a notice simulation: estimated number is 1, which is the value returned by aurora background.
Here Insert Picture Description
Fourth, after sending push show history:
Here Insert Picture Description
V. These are the simulation process in Aurora Developer Services push message.
The process is not a problem, we can begin to cool cool java development interface up. Aurora push stitching required json data, it can push the call interface.
Six, java core code:
a binding interface development:
bind employees and Aurora id, we need to push the phone all employees to log all stores under the store (Android and iOS).
Here is a troublesome place, that each mobile terminal reload app, Aurora id are likely to change when I'm not sure this is bound to generate a different aurora same device id, or a different device generates a new id Aurora, so the method I use is the id of these are binding, but the line will have a lot of dirty data, do not know how large cattle are processed.

Second, go its own business logic
Third, stitching Aurora push needed to json:

/**
     * 组装极光推送专用json串
     * @param alert
     * @param registrationId
     * @return json
     */
    private JSONObject generateJson(String alert, List<String> registrationId,Map<String,Object> android_extras,Map<String,Object> ios_extras){
        JSONObject json = new JSONObject();
        JSONArray platform = new JSONArray();//平台
        platform.add("android");
        platform.add("ios");

        JSONObject audience = new JSONObject();//推送目标
        audience.put("registration_id", registrationId);

        JSONObject notification = new JSONObject();//通知内容
        JSONObject android = new JSONObject();//android通知内容
        android.put("alert", alert);
        android.put("extras", android_extras);//android额外参数

        JSONObject ios = new JSONObject();//ios通知内容
        ios.put("alert", alert);
        ios.put("sound", "default");
        ios.put("extras", ios_extras);//ios额外参数
        notification.put("android", android);
        notification.put("ios", ios);

        JSONObject options = new JSONObject();//设置参数
        options.put("time_to_live", Integer.valueOf(time_to_live));
        options.put("apns_production", apns_production);

        json.put("platform", platform);
        json.put("audience", audience);
        json.put("notification", notification);
        json.put("options", options);
        return json;

    }

Push:

    @Value("${jiguang.appKey}")
    private String appKey;                         //极光appKey
    @Value("${jiguang.masterSecret}")
    private String masterSecret;                   //极光secret
    @Value("${jiguang.pushUrl}")
    private String pushUrl;                        //极光推送接口url
    @Value("${jiguang.apns_production}")
    private String apns_production;                //推送环境参数,设置true表示推送生产环境,false表示开发;默认推送生产环境
    @Value("${jiguang.time_to_live}")
    private String time_to_live;                   //离线消息保留时长,默认保留86400(1天),最长 10 天。设置为 0 表示不保留离线消息,只有推送当前在线的用户可以收到。

    @Override
    public ApiResponse jiGuangPush(JpushRequestModel jpushRequestModel) {
        //构建极光推送所需json
        log.info("极光推送带参:{}",jpushRequestModel);
        JSONObject object = generateJson(jpushRequestModel.getAlert(),jpushRequestModel.getRegistrationId(),jpushRequestModel.getAndroid_extras(),jpushRequestModel.getIos_extras());
        String data = object.toJSONString();
        log.info("-------极光推送构建的json消息:{}",data);

        //1.推送消息
        log.info("---------appKey:{},---------masterSecret:{}",appKey,masterSecret);
        String base64_auth_string = encryptBASE64(appKey + ":" + masterSecret);
        String authorization = "Basic " + base64_auth_string;
        log.info("Authorization值是:{}",authorization);
        HttpPost httpPost = new HttpPost(pushUrl);
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        Map<String,Object> map = new HashMap<>();
        try {
            StringEntity entity = new StringEntity(data, "UTF-8");
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            httpPost.setHeader("Authorization",authorization.trim());
            log.info("--------开始调用极光推送push-----");
            response = client.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
            log.info("--------push消息执行完毕-----,结果:{}",result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if(jsonObject.containsKey("error")){
                log.info("针对极光id为" + model.getAudience().getRegistration_id() + "的信息推送失败!");
                JSONObject error = JSONObject.parseObject(JSONObject.toJSONString(jsonObject.get("error")));
                log.info("错误信息为:" + error.get("message").toString());
                log.info("针对极光id为" + model.getAudience().getRegistration_id() + "的信息推送失败!");
                map.put("error",error);
            }else {
                log.info("----------极光推送成功!!!!!");
                map.put("sendno",jsonObject.get("sendno"));
                map.put("msg_id",jsonObject.get("msg_id"));
            }
        } catch (Exception e) {
            log.error("请求接口时偶遇异常,堆栈轨迹如下", e);
        }
        finally{
            if(response != null){
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(client != null){
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return ApiResponse.builder().setData(map);
    }

    /**
   * BASE64加密工具
   */
    public static String encryptBASE64(String str) {
        byte[] key = str.getBytes();
        BASE64Encoder base64Encoder = new BASE64Encoder();
        String strs = base64Encoder.encodeBuffer(key);
        return strs;
    }

Aurora Push Reference document: https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/
Aurora Push Case: https://v.qq.com/x/page/m01923a24ec.html

to sum up:

  • The official document is a good learning tool, I mainly use to share that way, welcome Paizhuan!
  • Write interface, not achieved enough, we should also consider whether its own interface easy to use, easy to use while others reflect reuse can be easily achieved. (We need to continue to optimize the code)
  • End mobile developers should be careful: the production environment to pass certificate production environment, packaged production environment
  • Aurora pushing itself is unstable in the Aurora platform testing services issued a notice to obtain estimates of the number is not on too frequent, do not worry, any one software, we can not guarantee 100% to meet the needs of users, only from more than similar software in contrast, can choose their own.
Published 253 original articles · won praise 76 · views 290 000 +

Guess you like

Origin blog.csdn.net/hongwei15732623364/article/details/87801279