版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/qq_37022150/article/details/75449290
参考 Java服务端向苹果APNS推送消息, 请关注之前的文章 :http://blog.csdn.net/qq_37022150/article/details/73991913
不废话,请直接看代码,向所有设备推送消息,注释非常的详细:
public class AndroidPushMsgToAll {
public static void main(String[] args)
throws PushClientException,PushServerException {
// 1. get apiKey and secretKey from developer console
// 从百度推送开发者控制台获取apiKey与 secretKey;
String apiKey = "WKqKYQyAhOLg2L4QlcwiWbAg";
String secretKey = "gSdkkKDkP397up4Kfmp7HGCuL7RoimQv";
// 创建PushKeyPair对象,使用到apiKey与secretKey;
PushKeyPair pair = new PushKeyPair(apiKey, secretKey);
// 2. build a BaidupushClient object to access released interfaces
// 创建 BaiduPushClient 对象,使用到PushKeyPair对象,与接口;
BaiduPushClient pushClient = new BaiduPushClient(pair,
BaiduPushConstants.CHANNEL_REST_URL);
// 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", "xxxxxxxx");
notification.put("description","xxxxxxx");
notification.put("notification_builder_id", 0);
notification.put("notification_basic_style",7);
notification.put("open_type", 2);
notification.put("pkg_content", null);
JSONObject jsonCustormCont = new JSONObject();
jsonCustormCont.put("key", "value"); //自定义内容,key-value
notification.put("custom_content", jsonCustormCont);
// 4. specify request arguments
// 具体的请求参数
PushMsgToAllRequest request = new PushMsgToAllRequest()
.addMsgExpires(new Integer(3600)).addMessageType(1)
// 透传
// .addMsgExpires(new Integer(3600)).addMessageType(0)
.addMessage(notification.toString()) //添加透传消息
// .addSendTime(System.currentTimeMillis() / 1000 + 120) // 设置定时推送时间,必需超过当前时间一分钟,单位秒.实例2分钟后推送
.addDeviceType(3);
// 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()));
}
}
}
}
如果有任何疑问,可以留言,关于单个设备推送,单个设备批量推送,标签推送,标签组合推等接口,如有需要请到该链接下载:http://download.csdn.net/my
更多文章,请关注:http://blog.csdn.net/qq_37022150?viewmode=list