java 集成极光推送

首先在pom文件中中引入Maven依赖

 



  cn.jpush.api
  jpush-client
  3.3.7


  cn.jpush.api
  jiguang-common
  1.1.1

其次,新建一个java类,可命名为Jpush,代码如下:

 

package com.sdyx.utils;

import cn.jiguang.common.ClientConfig;
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.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.Notification;

import java.util.Collection;
import java.util.Iterator;

public class JpushUtils {

    public static final String APP_KEY = "你的appkey";
    public static final String MASTER_SECRET ="你的appsecret";

    PushPayload payload;
    JPushClient jpushClient;


    public static void jpush(String alias,String title,String content){
        
       jpushClient = new JPushClient(MASTER_SECRET, APP_KEY, null, ClientConfig.getInstance());
            // For push, all you need do is to build PushPayload object.
            payload = buildPushObject_android_tag_alertWithTitle(alias,title,content);
        tests(jpushClient,payload);
    }

    //通知
    public static PushPayload buildPushObject_android_tag_alertWithTitle(String alias,String title,String content) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.alias(alias))
                .setNotification(Notification.android(content, title, null))
                .build();
    }
    //自定义消息
    public static PushPayload buildPushObject_android_tag_alertWithContent(String alias,String content) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android())
                .setAudience(Audience.alias(alias))
                .setMessage(Message.content(content))
                .build();
    }

    public static void tests(JPushClient jpushClient,PushPayload payload){
        try {
            PushResult result = jpushClient.sendPush(payload);
            System.out.println("Got result - " + result);

        } catch (APIConnectionException e) {
            // Connection error, should retry later
            System.out.println("Connection error, should retry later"+ e);

        } catch (APIRequestException e) {
            // Should review the error, and fix the request
            System.out.println("Should review the error, and fix the request"+ e);
            System.out.println("HTTP Status: " + e.getStatus());
            System.out.println("Error Code: " + e.getErrorCode());
            System.out.println("Error Message: " + e.getErrorMessage());
        }
    }
}

 

到此完成,在controller直接调用,传入对应的参数即可(appkey和appsecret到极光官网创建应用获取)

 

你可能感兴趣的:(java)