Java端百度云推送消息Demo

时间:2022-01-15 18:26:32

因为在做Java服务器有用到推送消息机制,于是到网上找了一下,就自己试着敲了一个demo。这个demo主要是简单的一个对app消息推送。

jar:百度云消息推送Java端的jar。

package xhw.demo;

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.BaiduPush;
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.PushMsgToSingleDeviceRequest;
import com.baidu.yun.push.model.PushMsgToSingleDeviceResponse; public class baiduyunDemo {
/**
* 初始化百度推送
* @return
*/
public static BaiduPushClient initPushClient(){ String apiKey="";//去百度云推送平台申请
String secretKey="";
PushKeyPair pair=new PushKeyPair(apiKey, secretKey);//设置两个属性
BaiduPushClient pushClient=new BaiduPushClient(pair, BaiduPushConstants.CHANNEL_REST_URL);//实例化BaiduPushClient对象
pushClient.setChannelLogHandler(new YunLogHandler() { @Override
public void onHandle(YunLogEvent arg0) {
System.out.println(arg0.getMessage()); }
});
return pushClient;
}
public static int pushOnlyMessage(String content,int pushType,int devType){
BaiduPushClient pushClient=initPushClient();
PushMsgToSingleDeviceRequest request=new PushMsgToSingleDeviceRequest();
// devType => 1: web 2: pc 3:android 4:ios 5:wp request.addDeviceType(devType);
request.addChannelId("");
request.addMessageType(pushType);
request.addMessage(content); try {
PushMsgToSingleDeviceResponse response=pushClient.pushMsgToSingleDevice(request); System.out.println("推送成功"+response.getMsgId()); } catch (PushClientException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (PushServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return 0; } }