闲来无事,搞了下百度云推送;顺手把博客给写了吧;其实不太想写,毕竟百度说明的很清楚,但还是给小白科普下吧;
其实以前一直用的都是个推的,本来感觉个推没什么不好,但突然听组长说今年个推涉及隐私,及推送IOS异常,所以转战百度云推送了,而且百度云推送还有统计功能;
百度帮助中心: http://push.baidu.com/doc/java/api
流程: 下载SDK > 登录个推平台 > 创建应用 > 获取API KEY > 下载demoAPP > 开发测试;
1.下载个推SDK
2.登录平台且创建应用(注意:暂时没有app,绑定包名可以默认为:com.baidu.demo)
3.查看API key 及SECRET KEY
(扫描二维码下载专属appdemo,点击app中的绑定-消息会推送到该demo下)
4.运行demoApp;
推送消息会在日志里面显示, 也会在通知中显示;(百度个推是默认2分钟后推送的,不过我改成及时推送也无感,不知道是不是和手机有关,我的消息偶尔会延迟)
5.准备开发
这里百度已经有明确文档了,简单不能在简单了,所以我就不重复了; 贴上链接: http://push.baidu.com/doc/java/quick_start
最后附上个人写百度云util工具类(初步的,仅提供部分功能),毕竟适合自己的才是最好的;
5个类:
impl实现类
util: commPUshUtil公共的查询方法
IbaiduPush: 接口类;
pushArgsVo类(可设置默认定义的属性参数);
IBaiduPush.java
import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;
import com.baidu.yun.push.model.MsgSendInfo;
/**
* <p class="detail">
* 功能:百度推送工具接口
* 可持续扩展: 目前仅包含ios,andorid推送,定时推送,获取单个消息,及统计消息;
* </p>
* @ClassName: IBaiduPush
* @version V1.0
* @date 2017-3-16
*/
public interface IBaiduPush {
/**
* <p class="detail">
* 功能:推送至所有设备(包含ios,android)
* </p>
*
* @author wuxw
* @param title
* @param content
* @throws
*/
public void pushMsgToAll(String title, String content)
throws PushClientException, PushServerException;
/**
* <p class="detail">
* 功能:统计安装了app的设备数,返回30天的所有统计项。
* </p>
* @author wuxw
* @return
* @throws PushClientException
* @throws PushServerException
* @throws
*/
public String queryStatisticDevice() throws PushClientException,
PushServerException;
/**
* <p class="detail">
* 功能:根据id,查询消息状态详情
* </p>
* @author wuxw
* @param msgId
* @return
* @throws PushClientException
* @throws PushServerException
* @throws
*/
public MsgSendInfo queryMsgStatus(String msgId) throws PushClientException,
PushServerException;
/********************* 共用方法 *********************/
/********************* android私有方法 ************************/
/**
* <p class="detail">
* 功能:向单个android用户推送通知
* </p>
* @author wuxw
* @param title
* @param content
* @param chinalId
* @throws PushClientException
* @throws PushServerException
* @throws
*/
public void androidPushMsgToSingleDevice(String title, String content,
String chinalId) throws PushClientException, PushServerException;
/**
* <p class="detail">
* 功能:向所有android用户推送通知
* </p>
* @author wuxw
* @param title
* @param description
* @throws PushClientException
* @throws PushServerException
* @throws
*/
public void androidPushMsgToAll(String title, String description)
throws PushClientException, PushServerException;
public void androidPushMsgToAll(String title, String description,
Long sendTime) throws PushClientException, PushServerException;
/**
* <p class="detail">
* 功能:向多个指定channelId - android用户推送通知
* </p>
* @author wuxw
* @param title
* @param description
* @param channelIds
* @throws PushClientException
* @throws PushServerException
* @throws
*/
public void androidPushBatchUniMsg(String title, String description,
String[] channelIds) throws PushClientException,
PushServerException;
/********************* ios私有方法 begin************************/
/********************* ios私有方法 begin************************/
/********************* ios私有方法 begin************************/
/**
* <p class="detail">
* 功能:向所有ios用户推送通知
* </p>
* @author wuxw
* @param alert
* @throws PushClientException
* @throws PushServerException
* @throws
*/
public void IOSPushNotificationToAll(String alert)
throws PushClientException, PushServerException;
public void IOSPushNotificationToAll(String alert, Long sendTime)
throws PushClientException, PushServerException;
/**
* <p class="detail">
* 功能:向单个ios用户推送通知
* </p>
* @author wuxw
* @param alert
* @param channelId
* @throws PushClientException
* @throws PushServerException
* @throws
*/
public void IOSPushNotificationToSingleDevice(String alert, String channelId)
throws PushClientException, PushServerException;
}
import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;
import com.baidu.yun.push.model.MsgSendInfo;
import cn.bforce.common.util.baidu.IBaiduPush;
import cn.bforce.common.util.baidu.util.BaiduAndroidPushUtil;
import cn.bforce.common.util.baidu.util.BaiduCommPushUtil;
import cn.bforce.common.util.baidu.util.BaiduIOSPushUtil;
public class BaiduPushUtilImpl implements IBaiduPush {
private BaiduAndroidPushUtil androidPushUtil;
private BaiduIOSPushUtil iosPushUtil;
private BaiduCommPushUtil commPushUtil;
public void pushMsgToAll(String title, String content)
throws PushClientException, PushServerException {
// TODO Auto-generated method stub
androidPushMsgToAll(title,content);
IOSPushNotificationToAll(content);
}
@Override
public String queryStatisticDevice() throws PushClientException,
PushServerException {
// TODO Auto-generated method stub
return commPushUtil.queryStatisticDevice();
}
@Override
public MsgSendInfo queryMsgStatus(String msgId) throws PushClientException,
PushServerException {
// TODO Auto-generated method stub
return androidPushUtil.queryMsgStatus(msgId);
}
@Override
public void androidPushMsgToSingleDevice(String title, String content,
String chinalId) throws PushClientException, PushServerException {
// TODO Auto-generated method stub
androidPushUtil.androidPushMsgToSingleDevice(title, content, chinalId);
}
@Override
public void androidPushMsgToAll(String title, String description)
throws PushClientException, PushServerException {
// TODO Auto-generated method stub
androidPushUtil.androidPushMsgToAll(title, description);
}
@Override
public void androidPushMsgToAll(String title, String description,
Long sendTime) throws PushClientException, PushServerException {
// TODO Auto-generated method stub
androidPushUtil.androidPushMsgToAll(title, description,sendTime);
}
@Override
public void androidPushBatchUniMsg(String title, String description,
String[] channelIds) throws PushClientException,
PushServerException {
// TODO Auto-generated method stub
androidPushUtil.androidPushBatchUniMsg(title, description, channelIds);
}
@Override
public void IOSPushNotificationToAll(String alert)
throws PushClientException, PushServerException {
// TODO Auto-generated method stub
iosPushUtil.IOSPushNotificationToAll(alert);
}
@Override
public void IOSPushNotificationToAll(String alert, Long sendTime)
throws PushClientException, PushServerException {
// TODO Auto-generated method stub
iosPushUtil.IOSPushNotificationToAll(alert,sendTime);
}
@Override
public void IOSPushNotificationToSingleDevice(String alert, String channelId)
throws PushClientException, PushServerException {
// TODO Auto-generated method stub
iosPushUtil.IOSPushNotificationToSingleDevice(alert,channelId);
}
public final BaiduAndroidPushUtil getAndroidPushUtil() {
return androidPushUtil;
}
public final void setAndroidPushUtil(BaiduAndroidPushUtil androidPushUtil) {
this.androidPushUtil = androidPushUtil;
}
public final BaiduIOSPushUtil getIosPushUtil() {
return iosPushUtil;
}
public final void setIosPushUtil(BaiduIOSPushUtil iosPushUtil) {
this.iosPushUtil = iosPushUtil;
}
public final BaiduCommPushUtil getCommPushUtil() {
return commPushUtil;
}
public final void setCommPushUtil(BaiduCommPushUtil commPushUtil) {
this.commPushUtil = commPushUtil;
}
}
import java.util.List;
import net.sf.json.JSONObject;
import com.baidu.yun.core.log.YunLogEvent;
import com.baidu.yun.core.log.YunLogHandler;
import com.baidu.yun.push.auth.PushKeyPair;
import com.baidu.yun.push.client.BaiduPushClient;
import com.baidu.yun.push.constants.BaiduPushConstants;
import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;
import com.baidu.yun.push.model.MsgSendInfo;
import com.baidu.yun.push.model.PushBatchUniMsgRequest;
import com.baidu.yun.push.model.PushBatchUniMsgResponse;
import com.baidu.yun.push.model.PushMsgToAllRequest;
import com.baidu.yun.push.model.PushMsgToAllResponse;
import com.baidu.yun.push.model.PushMsgToSingleDeviceRequest;
import com.baidu.yun.push.model.PushMsgToSingleDeviceResponse;
import com.baidu.yun.push.model.QueryMsgStatusRequest;
import com.baidu.yun.push.model.QueryMsgStatusResponse;
public class BaiduAndroidPushUtil {
public static PushKeyPair pair = new PushKeyPair(BaiduCommPushUtil.apiKey, BaiduCommPushUtil.secretKey);
public static BaiduPushClient pushClient = new BaiduPushClient(pair,
BaiduPushConstants.CHANNEL_REST_URL);
public BaiduAndroidPushUtil() {
// TODO Auto-generated constructor stub
pushClient.setChannelLogHandler (new YunLogHandler () {
@Override
public void onHandle(YunLogEvent event) {
System.out.println(event.getMessage());
}
});
}
/**
* <p class="detail">
* 功能:android向单个用户推送通知
* </p>
*
* @author wuxw
* @param title
* @param description
* @throws
*/
public static void androidPushMsgToSingleDevice(String title,
String description, String chinalId) throws PushClientException,
PushServerException {
// 3. register a YunLogHandler to get detail interacting information
// in this request.
pushClient.setChannelLogHandler(new YunLogHandler() {
@Override
public void onHandle(YunLogEvent event) {
System.out.println("环绕通知:" + event.getMessage());
}
});
try {
// 4. specify request arguments
// 创建 Android的通知
PushArgsVo argsVo = new PushArgsVo();
JSONObject notification = new JSONObject();
notification.put("title", title);
notification.put("description", description);
notification.put("notification_builder_id", 0);
notification.put("notification_basic_style", 4);
notification.put("open_type", 1);
notification.put("url", "http://push.baidu.com");
JSONObject jsonCustormCont = new JSONObject();
jsonCustormCont.put("key", "value"); // 自定义内容,key-value
notification.put("custom_content", jsonCustormCont);
argsVo.setNotification(notification);
argsVo.setChannelId(new String[] { chinalId });
PushMsgToSingleDeviceRequest request = new PushMsgToSingleDeviceRequest()
.addChannelId(argsVo.getChannelId()[0])
.addMsgExpires(argsVo.getMsgExpires())
. // message有效时间
addMessageType(argsVo.getMessageType())
.// 1:通知,0:透传消息. 默认为0 注:IOS只有通知.
addMessage(argsVo.getNotification().toString())
.addDeviceType(argsVo.getDeviceType());// 设置设备类型,deviceType
// => 1 for web, 2
// for pc, 3 for
// android, 4 for
// ios, 5 for wp.
// 5. http request
PushMsgToSingleDeviceResponse response = pushClient
.pushMsgToSingleDevice(request);
// Http请求结果解析打印
System.out.println("msgId: " + response.getMsgId() + ",sendTime: "
+ response.getSendTime());
} catch (PushClientException e) {
/*
* ERROROPTTYPE 用于设置异常的处理方式 -- 抛出异常和捕获异常,'true' 表示抛出, 'false' 表示捕获。
*/
if (BaiduPushConstants.ERROROPTTYPE) {
throw e;
} else {
e.printStackTrace();
}
} catch (PushServerException e) {
if (BaiduPushConstants.ERROROPTTYPE) {
throw e;
} else {
System.out.println(String.format(
"requestId: %d, errorCode: %d, errorMessage: %s",
e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
}
}
}
/**
* <p class="detail">
* 功能:向所有设备推送消息
* </p>
*
* @author wuxw
* @param title
* @param description
* @throws PushClientException
* @throws PushServerException
* @throws
*/
public static void androidPushMsgToAll(String title, String description)
throws PushClientException, PushServerException {
androidPushMsgToAll(title, description, null);
}
/**
* <p class="detail">
* 功能:安卓推送消息至所有设备(定时)
* </p>
*
* @author wuxw
* @param title
* @param description
* @param sendTime
* : 指定定时时间:
* @throws PushClientException
* @throws PushServerException
* @throws
*/
public static void androidPushMsgToAll(String title, String description,
Long sendTime) throws PushClientException, PushServerException {
// 3. register a YunLogHandler to get detail interacting information
// in this request.
pushClient.setChannelLogHandler(new YunLogHandler() {
@Override
public void onHandle(YunLogEvent event) {
System.out.println("环绕通知:" + event.getMessage());
}
});
try {
// 4. specify request arguments (argsVo,封装了默认参数配置)
PushArgsVo argsVo = new PushArgsVo();
String content = "{\"title\":\"" + title + "\",\"description\":\""
+ description + "\"}";
argsVo.setContent(content);
PushMsgToAllRequest request = new PushMsgToAllRequest()
.addMsgExpires(argsVo.getMsgExpires())
.addMessageType(argsVo.getMessageType())
.addMessage(argsVo.getContent()) // 添加透传消息
.addDeviceType(argsVo.getDeviceType());// 设置设备类型,deviceType
// => 1 for web, 2
// for pc, 3 for
// android, 4 for
// ios, 5 for wp.
// // 设置定时推送时间,必需超过当前时间一分钟,单位秒.实例2分钟后推送
if (null != sendTime) {
request.setSendTime(sendTime);
}
// 5. http request
PushMsgToAllResponse response = pushClient.pushMsgToAll(request);
// Http请求结果解析打印
System.out.println("msgId: " + response.getMsgId() + ",sendTime: "
+ response.getSendTime() + ",timerId: "
+ response.getTimerId());
System.out.println("当前时间: " + System.currentTimeMillis() / 1000);
} catch (PushClientException e) {
if (BaiduPushConstants.ERROROPTTYPE) {
throw e;
} else {
e.printStackTrace();
}
} catch (PushServerException e) {
if (BaiduPushConstants.ERROROPTTYPE) {
throw e;
} else {
System.out.println(String.format(
"requestId: %d, errorCode: %d, errorMessage: %s",
e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
}
}
}
/**
* <p class="detail">
* 功能:推送消息给指定设备(批量单播)。
* </p>
*
* @author wuxw
* @param title
* @param description
* @param channelIds
* @throws PushClientException
* @throws PushServerException
* @throws
*/
public static void androidPushBatchUniMsg(String title, String description,
String[] channelIds) throws PushClientException,
PushServerException {
// 3. register a YunLogHandler to get detail interacting information
// in this request.
pushClient.setChannelLogHandler(new YunLogHandler() {
@Override
public void onHandle(YunLogEvent event) {
System.out.println(event.getMessage());
}
});
try {
// 4. specify request arguments
// 创建Android通知
JSONObject notification = new JSONObject();
notification.put("title", title);
notification.put("description", description);
notification.put("notification_builder_id", 0);
notification.put("notification_basic_style", 4);
notification.put("open_type", 1);
notification.put("url", "http://push.baidu.com");
JSONObject jsonCustormCont = new JSONObject();
jsonCustormCont.put("key", "value"); // 自定义内容,key-value
notification.put("custom_content", jsonCustormCont);
PushBatchUniMsgRequest request = new PushBatchUniMsgRequest()
.addChannelIds(channelIds).addMsgExpires(new Integer(3600))
.addMessageType(1).addMessage(notification.toString())
.addDeviceType(3).addTopicId("BaiduPush");// 设置类别主题
// 5. http request
PushBatchUniMsgResponse response = pushClient
.pushBatchUniMsg(request);
// Http请求结果解析打印
System.out.println(String.format("msgId: %s, sendTime: %d",
response.getMsgId(), response.getSendTime()));
} catch (PushClientException e) {
if (BaiduPushConstants.ERROROPTTYPE) {
throw e;
} else {
e.printStackTrace();
}
} catch (PushServerException e) {
if (BaiduPushConstants.ERROROPTTYPE) {
throw e;
} else {
System.out.println(String.format(
"requestId: %d, errorCode: %d, errorMessage: %s",
e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
}
}
}
/**
* <p class="detail">
* 功能:根据id,查询消息状态详情
* </p>
*
* @author wuxw
* @param msgIds
* @throws PushClientException
* @throws PushServerException
* @throws
*/
public static MsgSendInfo queryMsgStatus(String msgId)
throws PushClientException, PushServerException {
try {
// 4. specify request arguments
QueryMsgStatusRequest request = new QueryMsgStatusRequest()
.addMsgIds(new String[] { msgId }).addDeviceType(3);
// 5. http request
QueryMsgStatusResponse response = pushClient
.queryMsgStatus(request);
// Http请求结果解析打印
System.out.println("totalNum: " + response.getTotalNum() + "\n"
+ "result:");
if (null != response) {
List<?> list = response.getMsgSendInfos();
for (int i = 0; i < list.size(); i++) {
Object object = list.get(i);
if (object instanceof MsgSendInfo) {
MsgSendInfo msgSendInfo = (MsgSendInfo) object;
StringBuilder strBuilder = new StringBuilder();
strBuilder.append(" {" + "msgId = "
+ msgSendInfo.getMsgId() + ",status = "
+ msgSendInfo.getMsgStatus() + ",sendTime = "
+ msgSendInfo.getSendTime() + ",success = "
+ msgSendInfo.getSuccessCount());
strBuilder.append("}\n");
System.out.println(strBuilder.toString());
return msgSendInfo;
}
}
}
} catch (PushClientException e) {
if (BaiduPushConstants.ERROROPTTYPE) {
throw e;
} else {
e.printStackTrace();
}
} catch (PushServerException e) {
if (BaiduPushConstants.ERROROPTTYPE) {
throw e;
} else {
System.out.println(String.format(
"requestId: %d, errorCode: %d, errorMessage: %s",
e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
}
}
return null;
}
public static void main(String[] args) throws PushClientException,
PushServerException {
// 推送单个通知
// androidPushMsgToSingleDevice("test","Hello Baidu push!","588912988050295920");
// 推送所有通知
// androidPushMsgToAll("test","Hello Baidu push!"+DateUtil.getCurrentTime());
// 查询单个消息状态详情
queryMsgStatus("XXXXXXXX");
}
}
BaiduCommPushUtil.java
import java.util.List;
import com.baidu.yun.core.log.YunLogEvent;
import com.baidu.yun.core.log.YunLogHandler;
import com.baidu.yun.push.auth.PushKeyPair;
import com.baidu.yun.push.client.BaiduPushClient;
import com.baidu.yun.push.constants.BaiduPushConstants;
import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;
import com.baidu.yun.push.model.KeyValueForDevice;
import com.baidu.yun.push.model.QueryStatisticDeviceRequest;
import com.baidu.yun.push.model.QueryStatisticDeviceResponse;
/**
* <p class="detail">
* 功能:Baidu消息推送
* </p>
* @ClassName: BaiduPushUtil
* @version V1.0
* @date 2017-3-15
*/
public class BaiduCommPushUtil{
public static String apiKey = "zICPVcNkKxUl5fmmeMsK65AM";
public static String secretKey = "cg6fmQgwDoUN8nUY3sd3h4D00OH6wDUH";
public static PushKeyPair pair = new PushKeyPair(apiKey, secretKey);
public static BaiduPushClient pushClient = new BaiduPushClient(pair,
BaiduPushConstants.CHANNEL_REST_URL);
BaiduCommPushUtil(){
/*
PushKeyPair pair = new PushKeyPair(apiKey, secretKey);
// 2. build a BaidupushClient object to access released interfaces
BaiduPushClient pushClient = new BaiduPushClient(pair,
BaiduPushConstants.CHANNEL_REST_URL);*/
// 3. register a YunLogHandler to get detail interacting information
pushClient.setChannelLogHandler (new YunLogHandler () {
@Override
public void onHandle(YunLogEvent event) {
System.out.println(event.getMessage());
}
});
}
/**
* <p class="detail">
* 功能:统计安装了app的设备数,返回30天的所有统计项。
* </p>
* @author wuxw
* @throws PushClientException
* @throws PushServerException
* @throws
*/
public static String queryStatisticDevice() throws PushClientException, PushServerException{
try {
// 4. specify request arguments
QueryStatisticDeviceRequest request = new QueryStatisticDeviceRequest().
addDeviceType(3);
// 5. http request
QueryStatisticDeviceResponse response = pushClient.
queryStatisticDevice(request);
// Http请求结果解析打印
if (null != response) {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("totalNum: " + response.getTotalNum()
+ "\n");
List<KeyValueForDevice> deviceStats = response.getResult();
strBuilder.append("result:{\n");
for (int i = 0; i < deviceStats.size(); i++) {
KeyValueForDevice keyValue = deviceStats.get(i);
if (i != 0) {
strBuilder.append(",");
}
strBuilder.append("" + keyValue.getKey() + ":{"
+ "newDeviceNum=" + keyValue.getValue().getNewDevNum()
+ ",delDeviceNum=" + keyValue.getValue().getDelDevNum()
+ ",onlineDeviceNum=" + keyValue.getValue().getOnlineDevNum()
+ ",addUpDeviceNum=" + keyValue.getValue().getAddUpDevNum()
+ ",totalDeviceNum=" + keyValue.getValue().getTotalDevNum()
+ "}");
}
strBuilder.append("}");
System.out.println(strBuilder.toString());
return strBuilder.toString();
}
} catch (PushClientException e) {
if (BaiduPushConstants.ERROROPTTYPE) {
throw e;
} else {
e.printStackTrace();
}
} catch (PushServerException e) {
if (BaiduPushConstants.ERROROPTTYPE) {
throw e;
} else {
System.out.println(String.format(
"requestId: %d, errorCode: %d, errorMessage: %s",
e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
}
}
return null;
}
}
baiduIOSPushUtil.java
import net.sf.json.JSONObject;
import com.baidu.yun.core.log.YunLogEvent;
import com.baidu.yun.core.log.YunLogHandler;
import com.baidu.yun.push.auth.PushKeyPair;
import com.baidu.yun.push.client.BaiduPushClient;
import com.baidu.yun.push.constants.BaiduPushConstants;
import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;
import com.baidu.yun.push.model.PushMsgToAllRequest;
import com.baidu.yun.push.model.PushMsgToAllResponse;
import com.baidu.yun.push.model.PushMsgToSingleDeviceRequest;
import com.baidu.yun.push.model.PushMsgToSingleDeviceResponse;
public class BaiduIOSPushUtil {
public PushKeyPair pair = new PushKeyPair(BaiduCommPushUtil.apiKey, BaiduCommPushUtil.secretKey);
public BaiduPushClient pushClient = new BaiduPushClient(pair,
BaiduPushConstants.CHANNEL_REST_URL);
public BaiduIOSPushUtil() {
// TODO Auto-generated constructor stub
pushClient.setChannelLogHandler (new YunLogHandler () {
@Override
public void onHandle(YunLogEvent event) {
System.out.println(event.getMessage());
}
});
}
public void IOSPushNotificationToAll(String alert)
throws PushClientException, PushServerException {
IOSPushNotificationToAll(alert, null);
}
public void IOSPushNotificationToAll(String alert, Long sendTime)
throws PushClientException, PushServerException {
// 3. register a YunLogHandler to get detail interacting information
// in this request.
pushClient.setChannelLogHandler(new YunLogHandler() {
@Override
public void onHandle(YunLogEvent event) {
System.out.println(event.getMessage());
}
});
try {
// 4. specify request arguments
PushArgsVo argsVo = new PushArgsVo();
// 创建IOS通知
JSONObject notification = new JSONObject();
JSONObject jsonAPS = new JSONObject();
jsonAPS.put("alert", alert);
jsonAPS.put("sound", "ttt"); // 设置通知铃声样式,例如"ttt",用户自定义。
notification.put("aps", jsonAPS);
notification.put("key1", "value1");
notification.put("key2", "value2");
PushMsgToAllRequest request = new PushMsgToAllRequest()
.addMsgExpires(argsVo.getMsgExpires()).addMessageType(1)
.addMessage(notification.toString()).addDepolyStatus(2)
.addDeviceType(4);
// 设置定时推送时间,必需超过当前时间一分钟,单位秒.实例2分钟后推送 System.currentTimeMillis() /
// 1000 + 120
if (null != sendTime) {
request.setSendTime(sendTime);
}
// 5. http request
PushMsgToAllResponse response = pushClient.pushMsgToAll(request);
// Http请求结果解析打印
System.out.println("msgId: " + response.getMsgId() + ",sendTime: "
+ response.getSendTime() + ",timerId: "
+ response.getTimerId());
} catch (PushClientException e) {
if (BaiduPushConstants.ERROROPTTYPE) {
throw e;
} else {
e.printStackTrace();
}
} catch (PushServerException e) {
if (BaiduPushConstants.ERROROPTTYPE) {
throw e;
} else {
System.out.println(String.format(
"requestId: %d, errorCode: %d, errorMessage: %s",
e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
}
}
}
public void IOSPushNotificationToSingleDevice(String alert, String channelId)
throws PushClientException, PushServerException {
// 3. register a YunLogHandler to get detail interacting information
// in this request.
pushClient.setChannelLogHandler(new YunLogHandler() {
@Override
public void onHandle(YunLogEvent event) {
System.out.println(event.getMessage());
}
});
try {
// 4. specify request arguments
PushArgsVo argsVo = new PushArgsVo();
// make IOS Notification
JSONObject notification = new JSONObject();
JSONObject jsonAPS = new JSONObject();
jsonAPS.put("alert", alert);
jsonAPS.put("sound", "ttt"); // 设置通知铃声样式,例如"ttt",用户自定义。
notification.put("aps", jsonAPS);
notification.put("key1", "value1");
notification.put("key2", "value2");
PushMsgToSingleDeviceRequest request = new PushMsgToSingleDeviceRequest()
.addChannelId(channelId)
.addMsgExpires(argsVo.getMsgExpires()). // 设置message的有效时间
addMessageType(1).// 1:通知,0:透传消息.默认为0 注:IOS只有通知.
addMessage(notification.toString()).addDeployStatus(2). // IOS,
// DeployStatus
// =>
// 1:
// Developer
// 2:
// Production.
addDeviceType(4);// deviceType => 3:android, 4:ios
// 5. http request
PushMsgToSingleDeviceResponse response = pushClient
.pushMsgToSingleDevice(request);
// Http请求结果解析打印
System.out.println("msgId: " + response.getMsgId() + ",sendTime: "
+ response.getSendTime());
} catch (PushClientException e) {
/*
* ERROROPTTYPE 用于设置异常的处理方式 -- 抛出异常和捕获异常,'true' 表示抛出, 'false' 表示捕获。
*/
if (BaiduPushConstants.ERROROPTTYPE) {
throw e;
} else {
e.printStackTrace();
}
} catch (PushServerException e) {
if (BaiduPushConstants.ERROROPTTYPE) {
throw e;
} else {
System.out.println(String.format(
"requestId: %d, errorCode: %d, errorMessage: %s",
e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
}
}
}
}
PushArgsVo.java
import net.sf.json.JSONObject;
/**
* <p class="detail">
* 功能:推送消息参数VO
* </p>
* @ClassName: PushArgsVo
* @version V1.0
* @date 2017-3-15
*/
public class PushArgsVo {
/**
* 设备Id
*/
private String[] channelId;
/**
* 设置消息的有效时间,单位秒,默认3600*5
*/
private Integer msgExpires = 3600 ;
/**
* 设置消息类型 1:通知,0:透传消息. 默认为0 注:IOS只有通知.
*/
private int messageType = 1;
/**
* 通知类型 - json消息内容: {\"title\":\"TEST\",\"description\":\"Hello Baidu push!\"}
*/
private JSONObject notification;
/**
* 设置设备类型,deviceType => 1 for web, 2 for pc, /3 for android, 4 for ios, 5 for wp
*/
private int deviceType = 3;
/**
* 通知消息类型: {\"title\":\"TEST\",\"description\":\"Hello Baidu push!\"}
*/
private String content;
/**
* 定时发送时间 System.currentTimeMillis() / 1000 + 120;
* 默认实时发送时,禁止reqeust.setSendTime()属性;
*/
private long sendTime;
public final String getContent() {
return content;
}
public final void setContent(String content) {
this.content = content;
}
public final long getSendTime() {
return sendTime;
}
public final void setSendTime(long sendTime) {
this.sendTime = sendTime;
}
public final String[] getChannelId() {
return channelId;
}
public final void setChannelId(String[] channelId) {
this.channelId = channelId;
}
public final Integer getMsgExpires() {
return msgExpires;
}
public final void setMsgExpires(Integer msgExpires) {
this.msgExpires = msgExpires;
}
public final int getMessageType() {
return messageType;
}
public final void setMessageType(int messageType) {
this.messageType = messageType;
}
public final JSONObject getNotification() {
return notification;
}
public final void setNotification(JSONObject notification) {
this.notification = notification;
}
public final int getDeviceType() {
return deviceType;
}
public final void setDeviceType(int deviceType) {
this.deviceType = deviceType;
}
}
baiduPushTest.java
import com.baidu.yun.push.exception.PushClientException;
import com.baidu.yun.push.exception.PushServerException;
public class BaiduPushTest {
public static void main(String[] args) throws PushClientException, PushServerException {
IBaiduPush tempUtilImpl = new BaiduPushUtilImpl();
//推送单个通知
//BaiduAndroidPushUtil.androidPushMsgToSingleDevice("test","Hello Baidu push!","XXXXXXXXXXXXXXX");
//推送所有通知
//tempUtilImpl.PushMsgToAll("test","Hello Baidu push-"+DateUtil.getCurrentTime()+"!");
//查询单个消息状态详情
tempUtilImpl.queryMsgStatus("XXXXXXXXXXXXXXXXXX");
//查看统计
tempUtilImpl.queryStatisticDevice();
}
}
这里说一声,下载SDK很重要,以下所有代码均是复制SDK中的提供的demo,未进行太多优化,因为SDK中代码已经实现了其功能了,我们改下KEY就可以了;
注: 因为项目未正式上线,以上代码均为测试代码,如正规使用,请勿必优化,比如通知格式优化,去除打印,异常释放等等;