极光推送总结
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了极光推送总结相关的知识,希望对你有一定的参考价值。
参考技术A 应用场景:在我们的项目中我们用的是创建视频会议和预警消息通知推送这两种情况,首先创建视频会议和中途邀请人参加会议我采用的是自定义推送消息,因为此应用场景传递的参数比较多,在推送过去之后android和ios可以很方便的将参数传递过去,但是我们考虑到邀请的所有人都在登录状态的时候才可以创建会议房间,我们采用的是腾讯视频会议的sdk,因为我们采用的是别名推送,当用户在登录的时候安卓端将用户uuid设置为别名,退出时取消别名,我在服务端根据传递过来的uuid利用别名查询registration_ids的数组大小是否为空判断当前用户是否设置别名,当邀请的所有人都设置了别名之后我才调用创建会议房间的接口。而预警消息推送我采用的是通知推送,当气象预警触发的时候我会采用通知推送的方式推送给app,这种方式比较简单。极光推送是给app推送消息的,我们首先需要在服务端集成maven依赖
<!-- 极光推送 -->
<groupId>cn.jpush.api
<artifactId>jpush-client
<version>3.2.3
</dependency>
接着我们需要了解极光推送有哪些推送方式,对于安卓和ios都适用的情况,我在项目中使用的是别名推送alias,(还有标签推送tag),推送方式又分为通知推送和自定义推送,通知推送能够显示在手机提示框中,而自定义推送却不能,我看安卓他们做的能跟微信视频一样的弹出一个会话框,看着挺不错的,这跟微信不同的是可以邀请多个,之前用阿里云的好像只能一对一,所以才换成腾讯视频会议的,好了,废话不多说,上我写的一个工具类,
package com.jpxx.homepage.homePage.service.utils;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
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.Notification;
import cn.jpush.api.push.model.Message;
import cn.jpush.api.push.model.PushPayload.Builder;
public class SendMessageUtils
private static StringAppKey="8a7880c6fb81ad494b224078";
/**
* JPush MasterSecret 极光推送平台生成的密钥
*/
private static StringMasterSecret="c0fc675c4c48f9bf35269cf4";
//两个参数分别填写你申请的masterSecret和appKey
private static JPushClientjPushClient=new JPushClient(MasterSecret,AppKey);
/**
* 通知推送
* 备注:推送方式不为空时,推送的值也不能为空;推送方式为空时,推送值不做要求
* @param type 推送方式:1、“tag”标签推送,2、“alias”别名推送
* @param value 推送的标签或别名值
* @param alert 推送的内容
*/
public static StringpushNotice(String type,String title,String value,String alert,int roomId,String MessageType,String name,String promoterAdavter,String meetingTitle,String sig)
Builder builder= PushPayload.newBuilder();
builder.setPlatform(Platform.all());//设置接受的平台,all为所有平台,包括安卓、ios、和微软的
//设置如果用户不在线、离线消息保存的时间
Options options=Options.sendno();
options.setTimeToLive(86400l); //设置为86400为保存一天,如果不设置默认也是保存一天
builder.setOptions(options);
builder.setMessage(Message.newBuilder()
.setMsgContent(value)
.setTitle(title)
.addExtra("roomId",roomId)
.addExtra("MessageType",MessageType)
.addExtra("name",name)
.addExtra("promoterAdavter",promoterAdavter)
.addExtra("meetingTitle",meetingTitle)
.addExtra("userSig",sig)
.build());
//设置推送方式
if(type.equals("alias"))
builder.setAudience(Audience.alias(value));//根据别名推送
else if(type.equals("tag"))
builder.setAudience(Audience.tag(value));//根据标签推送
else
builder.setAudience(Audience.all());//Audience设置为all,说明采用广播方式推送,所有用户都可以接收到
//设置为采用通知的方式发送消息
builder.setNotification(Notification.alert(alert));
PushPayload pushPayload=builder.build();
System.out.println("ggggggg"+pushPayload);
try
//进行推送,实际推送就在这一步
//System.out.println("zzzzzzzzz "+jPushClient.sendPush(pushPayload));
PushResult pushResult=jPushClient.sendPush(pushPayload);
return "success";
catch(Exception e)
System.out.println("异常 "+e);
e.printStackTrace();
return "fail";
/**
* 自定义消息推送
* 备注:推送方式不为空时,推送的值也不能为空;推送方式为空时,推送值不做要求
* @param type 推送方式:1、“tag”标签推送,2、“alias”别名推送
* @param value 推送的标签或别名值
* @param alert 推送的内容
*/
public static StringpushMsg(String type,String title,String value,String alert,int roomId,String MessageType,String name,String promoterAdavter,String meetingTitle,String sig)
Builder builder= PushPayload.newBuilder();
builder.setPlatform(Platform.all());//设置接受的平台
if(type.equals("alias"))
builder.setAudience(Audience.alias(value));//别名推送
else if(type.equals("tag"))
builder.setAudience(Audience.tag(value));//标签推送
else
builder.setAudience(Audience.all());//Audience设置为all,说明采用广播方式推送,所有用户都可以接收到
Message.Builder newBuilder=Message.newBuilder();
newBuilder.setMsgContent(alert);//消息内容
newBuilder.setTitle(title);
newBuilder.addExtra("roomId",roomId);
newBuilder.addExtra("MessageType",MessageType);
newBuilder.addExtra("name",name);
newBuilder.addExtra("promoterAdavter",promoterAdavter);
newBuilder.addExtra("meetingTitle",meetingTitle);
newBuilder.addExtra("userSig",sig);
Message message=newBuilder.build();
builder.setMessage(message);
PushPayload pushPayload=builder.build();
try
PushResult pushResult=jPushClient.sendPush(pushPayload);
System.out.println(pushResult.isResultOK());
return "success";
catch(Exception e)
e.printStackTrace();
return "fail";
public static void main(String[] args)
//给标签为kefu的用户进行消息推送
//SendMessageUtils.pushMsg("alias","标题","5b9022746e284ea0992e3baa983035dc","你有新的任务,请及时处理",111,"meetingType","name","avater","meetingTitle","");
//sendNotificationWirhAlias_Ios("zzzzzzzzzzzz","uuid");
//String result = SendMessageUtils.pushNotice("alias","标题","5b9022746e284ea0992e3baa983035dc","你有新的任务,请及时处理",111,"meetingType","name","avater","meetingTitle","");
//System.out.println("返回结果"+result);
/*String result = SendMessageUtils.pushNotice("alias","预警标题","5b9022746e284ea0992e3baa983035dc","dddd",0,"warnType","","","",""); //userDto.getUuId()
System.out.println("result "+result);*/
//根据uuid查询别名信息是否存在
String result = HttpRequestUtil.JGUtil("https://device.jpush.cn/v3/aliases/5b9022746e284ea0992e3baa983035dc", "8a7880c6fb81ad494b224078","c0fc675c4c48f9bf35269cf4");//get请求
//String result = HttpRequestUtil.interfaceUtil("http://172.16.2.207:6606/daibancontroller.do?getDbxxNum", "","ydswtapp","eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ7XCJjbGllbnRJZFwiOlwieWRzd3RhcHBcIixcImxvZ2luVGltZVwiOjE1NTYwMDY1NDU4MzksXCJ1c0lkXCI6MjM5OSxcInVzZXJSb2xlXCI6XCJBRE1JTlwiLFwidXVJZFwiOlwiNDAyODgxZTUzYzdmMGRkZTAxM2M3ZjI5ZWQ4ZTAwMTZcIn0iLCJpc3MiOiJhdXRoMCIsImV4cCI6MTg3MTM2NjU0NSwiaWF0IjoxNTU2MDA2NTQ1fQ.Cy3-eDD4OEYhJlldvtJsymALRVGwP466TmBrSQJQGUo");//get请求
System.out.println("result "+result);
因为我要根据前端传来的uuid判断当前用户是否登录,所以我对http方法进行了稍微改装,根据极光的api文档(文档写的不是很好找),以下是我改装的
/**
*
* 极光专用
*/
public static StringJGUtil(String path,String appKey,String masterSecret)
String str ="";
try
URL url =new URL(path);
//打开和url之间的连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
PrintWriter out =null;
/**设置URLConnection的参数和普通的请求属性****start***/
String base64String=appKey+":"+masterSecret;
System.out.println("拼接的 "+base64String);
String str2=base64String;
String encode =new BASE64Encoder().encode(str2.getBytes());
System.out.println("编码过后:"+encode);
String auth ="Basic "+encode;
System.out.println("最终的 "+auth);
conn.setRequestProperty("Authorization", auth);
conn.setRequestProperty("Content-Type", "application/json");
//conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
/**设置URLConnection的参数和普通的请求属性****end***/
//设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
//最常用的Http请求无非是get和post,get请求可以获取静态页面,也可以把参数放在URL字串后面,传递给servlet,
//post与get的 不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("GET");//GET和POST必须全大写
/**GET方法请求*****start*/
/**
* 如果只是发送GET方式请求,使用connet方法建立和远程资源之间的实际连接即可;
* 如果发送POST方式的请求,需要获取URLConnection实例对应的输出流来发送请求参数。
* */
conn.connect();
/**GET方法请求*****end*/
/***POST方法请求****start*/
/*out = new PrintWriter(conn.getOutputStream());//获取URLConnection对象对应的输出流 out.print(data);//发送请求参数即数据 out.flush();//缓冲数据*/
/***POST方法请求****end*/
//获取URLConnection对象对应的输入流
InputStream is = conn.getInputStream();
//构造一个字符流缓存
BufferedReader br =new BufferedReader(new InputStreamReader(is));
while ((str = br.readLine()) !=null)
str =new String(str.getBytes(), "UTF-8");//解决中文乱码问题
System.out.println("wwwww"+str);
return str;
//关闭流
is.close();
//断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
//固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些。
conn.disconnect();
System.out.println("完整结束");
catch (Exception e)
e.printStackTrace();
return "success";
好了,以后再写类似的就会写了,这里附上极光文档的链接 https://docs.jiguang.cn/jpush/server/push/server_overview/
极光推送_总结_01_Java实现极光推送
一、代码实现
1.配置类—Env.java
package com.ray.jpush.config; /**@desc : 极光推送接入配置 * * @author: shirayner * @date : 2017年9月27日 下午4:57:36 */ public class Env { /** * 1.极光推送后台APPKEY,MASTER_SECRET */ public static final String APP_KEY = "354fb5c3dd4249ec11bc545d"; public static final String MASTER_SECRET = "8976605bf8a9ef9d8d97a8c2"; }
2.消息服务类—MessageService.java
package com.ray.jpush.service.message; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.ray.jpush.util.CommonUtil; import com.ray.jpush.util.HttpHelper; /**@desc : 极光推送消息服务 * * @author: shirayner * @date : 2017年11月29日 下午2:24:16 */ public class MessageService { private static final Logger log= LogManager.getLogger(MessageServiceTest.class); //1.发送通知 private static final String SEND_NOTIFICATION_URL="https://api.jpush.cn/v3/push"; /** * @desc : 1.调用极光API * * @param url 接口url * @param registration_id 注册id * @param alert 通知内容 * @param appKey * @param masterSecret * @return * JSONObject */ public static JSONObject sendNotification(String registration_id,String alert,String appKey,String masterSecret) { String base64_auth_string = CommonUtil.encryptBASE64(appKey + ":" + masterSecret); String authorization = "Basic " + base64_auth_string; String data=generateJson(registration_id,alert).toString(); log.debug("authorization:"+authorization); log.debug("data:"+data); return HttpHelper.doPost(SEND_NOTIFICATION_URL, data, authorization); } /** * @desc : 2.拼装请求json * * @param registration_id 注册id * @param alert 通知内容 * @return * JSONObject */ private static JSONObject generateJson(String registration_id,String alert){ JSONObject json = new JSONObject(); JSONArray platform = new JSONArray(); //1.推送平台设置 platform.add("android"); platform.add("ios"); JSONObject audience = new JSONObject(); //2.推送设备指定,即推送目标 JSONArray registrationIdList = new JSONArray(); registrationIdList.add(registration_id); audience.put("registration_id", registrationIdList); JSONObject notification = new JSONObject(); //3.通知内容 JSONObject android = new JSONObject(); //3.1 android通知内容 android.put("alert", alert); //设置通知内容 android.put("builder_id", 1); JSONObject android_extras = new JSONObject();//android额外参数 android_extras.put("type", "infomation"); android.put("extras", android_extras); JSONObject ios = new JSONObject();//3.2 ios通知内容 ios.put("alert", alert); ios.put("sound", "default"); ios.put("badge", "+1"); JSONObject ios_extras = new JSONObject();//ios额外参数 ios_extras.put("type", "infomation"); ios.put("extras", ios_extras); notification.put("android", android); notification.put("ios", ios); json.put("platform", platform); json.put("audience", audience); json.put("notification", notification); return json; } }
3.HttpHelper工具类—HttpHelper.java
package com.ray.jpush.util; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.util.EntityUtils; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; /** * HTTP请求工具类 */ public class HttpHelper { /** * @desc :1.发送POST请求-极光推送 * * @param url 接口url * @param data 请求包体 * @param authorization 验证字段,Authorization: Basic base64_auth_string * 其中 base64_auth_string 的生成算法为:base64(appKey:masterSecret) * 即,对 appKey 加上冒号,加上 masterSecret 拼装起来的字符串,再做 base64 转换。 * @return * @throws Exception * JSONObject */ public static JSONObject doPost(String url, String data ,String authorization) { //1.生成一个请求 HttpPost httpPost = new HttpPost(url); //2.配置请求属性 //2.1 设置请求超时时间 RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(100000).setConnectTimeout(100000).build(); httpPost.setConfig(requestConfig); //2.2 设置数据传输格式-json httpPost.addHeader("Content-Type", "application/json"); //2.3 设置Authorization httpPost.addHeader("Authorization", authorization.trim()); //2.3 设置请求实体,封装了请求参数 StringEntity requestEntity = new StringEntity(data, "utf-8"); httpPost.setEntity(requestEntity); //3.发起请求,获取响应信息 //3.1 创建httpClient CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; try { //3.3 发起请求,获取响应 response = httpClient.execute(httpPost, new BasicHttpContext()); if (response.getStatusLine().getStatusCode() != 200) { System.out.println("request url failed, http code=" + response.getStatusLine().getStatusCode() + ", url=" + url); return null; } //获取响应内容 HttpEntity entity = response.getEntity(); if (entity != null) { String resultStr = EntityUtils.toString(entity, "utf-8"); System.out.println("POST请求结果:"+resultStr); //解析响应内容 JSONObject result = JSON.parseObject(resultStr); //请求失败 if (result.getInteger("errcode")!=null && 0 != result.getInteger("errcode")) { System.out.println("request url=" + url + ",return value="); System.out.println(resultStr); int errCode = result.getInteger("errcode"); String errMsg = result.getString("errmsg"); try { throw new Exception("error code:"+errCode+", error message:"+errMsg); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //请求成功 } else { return result; } } } catch (IOException e) { System.out.println("request url=" + url + ", exception, msg=" + e.getMessage()); e.printStackTrace(); } finally { if (response != null) try { response.close(); //释放资源 } catch (IOException e) { e.printStackTrace(); } } return null; } }
4.通用工具类—CommonUtil.java
package com.ray.jpush.util; import sun.misc.BASE64Encoder; /**@desc : * * @author: shirayner * @date : 2017年11月29日 下午3:11:33 */ public class CommonUtil { /** * @desc :BASE64加密工具 * * @param str 待加密字符串 * @return * String */ public static String encryptBASE64(String str) { byte[] key = str.getBytes(); BASE64Encoder base64Encoder = new BASE64Encoder(); String strs = base64Encoder.encodeBuffer(key); return strs; } }
5.消息服务测试类—MessageServiceTest.java
package com.ray.jpush.service.message; import org.junit.Test; import com.ray.jpush.config.Env; /**@desc : 极光推送测试类 * * @author: shirayner * @date : 2017年11月29日 下午3:54:42 */ public class MessageServiceTest { /** * @desc :1.发送通知 * * void */ @Test public void testSendNotification() { String registration_id="121c83f760211fa5944"; //String alert="hello,my honey!"; String alert="您好:\\\\n 于岩军在2017-11-15提出了一张金额为5的费用报销单 BX10017110076 ,需要审批! \\\\n\\\\n\\\\n===================================================================\\\\n\\\\n秒针费用管理系统\\\\n\\\\n本邮件由系统自动发送,请勿回复。"; String appKey=Env.APP_KEY; String masterSecret=Env.MASTER_SECRET; MessageService.sendNotification(registration_id, alert, appKey, masterSecret); } }
二、参考资料
1.极光推送经验之谈-Java后台服务器实现极光推送的两种实现方式
以上是关于极光推送总结的主要内容,如果未能解决你的问题,请参考以下文章