极光推送消息——Alias别称方式(Andirod)

时间:2022-03-19 19:19:40

1、pom文件引入相关jar包

 <!--极光推送消息start-->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency> <dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jpush-client</artifactId>
<version>3.3.</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions> </dependency> <dependency>
<groupId>cn.jpush.api</groupId>
<artifactId>jiguang-common</artifactId>
<version>1.1.</version>
</dependency> <dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1..Final</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.3</version>
</dependency> <!--极光推送消息end-->

2、提供相关包装好的类

(1)消息封装类

package com.test.entity.common;

import com.google.gson.JsonObject;

import java.util.List;
import java.util.Map; /**
* 极光推送消息类
*/
public class JPushDeviceBean {
private String token;
private String alias_value;//别名值
private String registration_id;
private List<String> username;//所有用户别名
private String title;//标题
private String fsmessagecontent;//内容
private Integer count;//角标数
private Map<String, String> extrasMap;
private JsonObject extra; public JsonObject getExtra() {
return extra;
} public void setExtra(JsonObject extra) {
this.extra = extra;
} public Map<String, String> getExtrasMap() {
return extrasMap;
} public void setExtrasMap(Map<String, String> extrasMap) {
this.extrasMap = extrasMap;
} public String getToken() {
return token;
} public void setToken(String token) {
this.token = token;
} public String getAlias_value() {
return alias_value;
} public void setAlias_value(String alias_value) {
this.alias_value = alias_value;
} public String getRegistration_id() {
return registration_id;
} public void setRegistration_id(String registration_id) {
this.registration_id = registration_id;
} public List<String> getUsername() {
return username;
} public void setUsername(List<String> username) {
this.username = username;
} public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
} public String getFsmessagecontent() {
return fsmessagecontent;
} public void setFsmessagecontent(String fsmessagecontent) {
this.fsmessagecontent = fsmessagecontent;
} public Integer getCount() {
return count;
} public void setCount(Integer count) {
this.count = count;
}
}

(2)工具类

package com.test.util;

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.audience.AudienceTarget;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import java.util.Map; public class JPushDevice { protected static final Logger LOG =LoggerFactory.getLogger(JPushDevice.class); private static final String URL="https://device.jpush.cn";//极光访问URL
public static long timeToLive=***;//10天 //privatestaticJPushClientjpushClient= newJPushClient(masterSecret,appKey,null,ClientConfig.getInstance()); //  //对于推送,您所需要做的就是构建PushPayload对象。
//  PushPayloadpayload=buildPushObject_ios_audienceMore_messageWithExtras();
//  PushResultresult=jpushClient.sendPush(payload); public static PushPayload buildPushObject_android_tag_alertWithTitle(String username){
return PushPayload.newBuilder()
.setPlatform(Platform.all())
.setAudience(Audience.alias(username))
.setNotification(Notification.alert("ALERT"))
.build();
}
//弹框
public static PushPayload buildPushObject_ios_audienceMore_messageWithExtras(String username){
return PushPayload.newBuilder()
.setPlatform(Platform.all())
.setAudience(Audience.alias(username))
.setMessage(Message.newBuilder()
.setMsgContent("您有一条回复内容。。")
.addExtra("from","JPush")
.build())
.build();
}
//推送全部平台(一个用户)(无角标)
public static PushPayload oneName(String username, String title, String fsmessagecontent,
Map<String, String> extrasMap, JsonObject extra){
return PushPayload.newBuilder()
.setPlatform(Platform.all())//推送全部平台
.setAudience(Audience.newBuilder()//推送目标:别名、标签、注册ID、分群、广播等。
.addAudienceTarget(AudienceTarget.alias(username))
.build())
.setMessage(Message.newBuilder()
.setMsgContent(fsmessagecontent)//消息内容
// .setTitle(count.toString())//当做安卓的角标数
.addExtra("from","JPush")//应用内消息通道
.build())
.setNotification(Notification.newBuilder()//notification:通知内容体。是被推送到客户端的内容
.addPlatformNotification(IosNotification.newBuilder()//iOS
.setAlert(title)//弹框显示标题
// .setBadge(count)//角标
.build())
.addPlatformNotification(AndroidNotification.newBuilder()//安卓
.setAlert(fsmessagecontent)//弹框显示内容
.setTitle(title)//弹框显示标题
.addExtras(extrasMap)
.addExtra("extra",extra)
.build())
.build())
.build();
}
//推送全部平台(传多个别名用户)(有角标)
public static PushPayload AllName(String[] username,String title,String fsmessagecontent,Integer count){
return PushPayload.newBuilder()
.setPlatform(Platform.all())//推送全部平台
.setAudience(Audience.newBuilder()//推送目标:别名、标签、注册ID、分群、广播等。
.addAudienceTarget(AudienceTarget.alias(username))//别名可以是数组为并集,一次只能存1000个
.build())
.setMessage(Message.newBuilder()
.setMsgContent(fsmessagecontent)//消息内容
.setTitle(count.toString())//当做安卓的角标数
.addExtra("from","JPush")//应用内消息通道
.build())
.setNotification(Notification.newBuilder()//notification:通知
.addPlatformNotification(IosNotification.newBuilder()//iOS
.setAlert(title)//弹框显示标题
.setBadge(count)//角标
.build())
.addPlatformNotification(AndroidNotification.newBuilder()//安卓
.setAlert(fsmessagecontent)//弹框显示内容
.setTitle(title)//弹框显示标题
.build())
.build())
.build();
}
}

(3)实现类

package com.test.controller.common;

import static com.yjl.util.UploadUtil.getErrorMsg;
import static com.yjl.util.UploadUtil.getYjlResponseModel;
import static com.yjl.util.UploadUtil.isSuccess;
import static com.yjl.util.UploadUtil.setErrorMsg;
import static com.yjl.util.UploadUtil.setSuccess;
import static com.yjl.util.UploadUtil.setYjlResponseModel; 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.PushPayload;
import com.google.gson.Gson;
import com.yjl.entity.common.JPushDeviceBean;
import com.yjl.entity.common.YJLResponseModel;
import com.yjl.util.HttpClientUtil;
import com.yjl.util.JPushDevice;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONObject;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; @Controller
@RequestMapping("/JPushDevice")
public class JPushDeviceController{ private static Logger logger = LoggerFactory.getLogger(JPushDeviceController.class); //极光访问URL
private static final String URL = "https://device.jpush.cn";
//极光用户名
private static final String APPKEY ="极光平台生成的app的appkey";
//极光密码
private static final String MASTERSECRET ="极光平台生成的app的mastersecret"; //1.推送一个人
@RequestMapping(value = "getOneJPushDevice", method = RequestMethod.POST)
@ResponseBody
public PushResult getOneJPushDevice(@RequestBody JPushDeviceBean j) {
String aliases = getAliases(j.getAlias_value());
//一个别名
PushResult pResult = new PushResult();
//别名;
if(StringUtils.isNotBlank(aliases)){
//极光推送
JPushClient jpushClient = new JPushClient(MASTERSECRET,APPKEY,null,ClientConfig.getInstance());
PushPayload payload = JPushDevice.oneName(aliases, j.getTitle(), j.getFsmessagecontent(),j.getExtrasMap(),j.getExtra());
try {
pResult = jpushClient.sendPush(payload);
System.out.println("Got result 推送一个人 - 3" + pResult );
Thread.sleep();
// 请求结束后,调用 NettyHttpClient 中的 close 方法,否则进程不会退出。
jpushClient.close();
}
catch (APIConnectionException e) {
e.printStackTrace();
}
catch (APIRequestException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
return pResult;
}
//2.推送多人//先循环判断别名
@RequestMapping(value = "getAllJPushDevice", method = RequestMethod.POST)
@ResponseBody
public YJLResponseModel getAllJPushDevice(@RequestBody JPushDeviceBean j) {
setYjlResponseModel(new YJLResponseModel());
setErrorMsg("");
setSuccess(false);
List<String> ulist = j.getUsername();
//判断过得别名数组
if(null!=ulist && !ulist.isEmpty()){
String[] username = ulist.toArray(new String[ulist.size()]);
//转化为数组
//极光推送
JPushClient jpushClient = new JPushClient(MASTERSECRET,APPKEY,null, ClientConfig.getInstance());
PushPayload payload = JPushDevice.AllName(username, j.getTitle(), j.getFsmessagecontent(), j.getCount());
//用户别名数组1000个一次,标题,内容,角标数
PushResult pResult;
try {
pResult = jpushClient.sendPush(payload);
setSuccess(true);
System.out.println("Got result - " + new Gson().toJson(pResult) );
try {
Thread.sleep();
}
catch (InterruptedException e) {
e.printStackTrace();
}
// 请求结束后,调用 NettyHttpClient 中的 close 方法,否则进程不会退出。
jpushClient.close();
}
catch (APIConnectionException e) {
e.printStackTrace();
}
catch (APIRequestException e) {
e.printStackTrace();
}
finally {
getYjlResponseModel().setErrorMsg(getErrorMsg());
getYjlResponseModel().setSuccess(isSuccess());
}
}
return getYjlResponseModel();
}
//查询别名是否存在
public static String getAliases(String aliases){
String alia ="";
JPushDeviceBean j = new JPushDeviceBean();
j.setAlias_value(aliases);
YJLResponseModel map = getJPushDeviceAliases(j);
//查询是否含有别名
Map<String, Object> ma = (Map<String, Object>)map.getData();
if(ma.containsKey("registration_ids")){
List<String> list = (List<String>)ma.get("registration_ids");
//查询registration_ids的值不为空则含有该别名
if(null!=list && !list.isEmpty()){
System.out.println("查询别名----"+new Gson().toJson(list));
//在此内可调用极光的推送方法
alia = aliases;
//如果存在就给返回该别名
}
}
return alia;
}
//--------------------查询别名的方法-------------------------------------------
//查询别名(找不到统计项就是 null,否则为统计项的值。)
@RequestMapping(value = "getJPushDeviceAliases", method = RequestMethod.POST)
@ResponseBody
public static YJLResponseModel getJPushDeviceAliases(@RequestBody JPushDeviceBean ht) {
setYjlResponseModel(new YJLResponseModel());
setErrorMsg("");
setSuccess(false);
JSONObject response = null;
try {
StringBuilder url = new StringBuilder(URL).append("/v3/aliases/"+ht.getAlias_value());
String authorValue = getBase64();
Map<String, String> para = new HashMap<>();
response = HttpClientUtil.doGet(url.toString(), authorValue, para);
if (StringUtils.isNotEmpty((String)response.get("error"))) {
logger.info("getAliases:url+params----" + url + para);
throw new Exception();
}
setSuccess(true);
}
catch (Exception e) {
e.printStackTrace();
logger.error("getAliases:url+params----" + e);
}finally {
getYjlResponseModel().setErrorMsg(getErrorMsg());
getYjlResponseModel().setSuccess(isSuccess());
getYjlResponseModel().setData(response);
}
return getYjlResponseModel();
} //String转base64
public static String getBase64(){
Base64 base64 = new Base64();
String base64Sign ="";
String string = APPKEY+":"+MASTERSECRET;
try {
base64Sign = base64.encodeToString(string.getBytes("UTF-8"));
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return " Basic "+base64Sign;
} //测试一下
public static void main(String[] args) {
JPushDeviceController JPushDeviceController = new JPushDeviceController();
JPushDeviceBean jd = new JPushDeviceBean();
jd.setAlias_value("");//此处为待推送的用户id
jd.setTitle("推送消息");
jd.setFsmessagecontent("测试一下服务器端");
PushResult pushResult = JPushDeviceController.getOneJPushDevice(jd);
System.out.println(pushResult); }
}

3.测试一下

 //测试一下
public static void main(String[] args) {
JPushDeviceController JPushDeviceController = new JPushDeviceController();
JPushDeviceBean jd = new JPushDeviceBean();
jd.setAlias_value("");
jd.setTitle("推送消息");
jd.setFsmessagecontent("测试一下服务器端");
Map<String,String> extrasParam = new HashMap<>();
extrasParam.put("额外参数1","额外参数内容1");
jd.setExtrasMap(extrasParam);
PushResult pushResult = JPushDeviceController.getOneJPushDevice(jd);
System.out.println(pushResult); }