1. 程式人生 > >[Push]百度訊息推送的應用

[Push]百度訊息推送的應用

推送技術是指通過客戶端與伺服器端建立長連結,客戶端可以接收由伺服器端不定時傳送的訊息,在客戶機/伺服器的應用程式中,推送技術能夠向客戶機傳送資料而無需其發出請求,例如傳送電子郵件。相比較而言,全球資訊網卻是基於拉技術(Pull Technology),因此客戶機瀏覽器必須事先向網頁發出請求,所需資訊才能被傳送過來。

手機推送服務的原理很簡單,就是通過建立一條手機與伺服器的連線鏈路,當有訊息需要傳送到手機時,通過此鏈路傳送即可

/**
  * 初始化百度推送
 * @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; } /** * 訊息推送 * @return */ public static int pushOnlyMessage(String content,int pushType,int devType){ BaiduPushClient pushClient=initPushClient(); //得到百度推送 PushMsgToSingleDeviceRequest request=new PushMsgToSingleDeviceRequest(); request.addMsgExpires(new Integer(3600)) //訊息有效時間 request.addDeviceType(devType); // devType => 1: web 2: pc 3:android 4:ios 5:wp request.addChannelId(""); // 廣播ID request.addMessageType(pushType); // request.addMessage(content); try { PushMsgToSingleDeviceResponse response=pushClient.pushMsgToSingleDevice(request); System.out.println("推送成功"+response.getMsgId()); } catch (PushClientException e) { e.printStackTrace(); } catch (PushServerException e) { e.printStackTrace(); } return 0; }


例項程式碼:

//向安卓移動端推送
public String sendAndroidMessage(String messageTitle, String messageContent, String[] channelIds)throws PushClientException,PushServerException {
    	
    	//1. 建立PushKeyPair用於app的合法身份認證apikey和secretKey可在應用詳情中獲取
	PushKeyPair pair = new PushKeyPair(apiKeyForAndorid, secretKeyForAndorid);
	// 2. 建立BaiduPushClient,訪問SDK介面
	BaiduPushClient pushClient = new BaiduPushClient(pair,BaiduPushConstants.CHANNEL_REST_URL);
	// 3. 註冊YunLogHandler,獲取本次請求的互動資訊
	pushClient.setChannelLogHandler(new YunLogHandler() {
		@Override
		public void onHandle(YunLogEvent event) {
			log.debug(event.getMessage());
		}
	});
	try {
		// 4. 設定請求引數,建立請求例項
		//建立Android通知
		JSONObject notification = new JSONObject();
		notification.put("title", messageTitle);		//標題
		notification.put("description",messageContent);		//內容
		notification.put("notification_builder_id", 0);		//客戶端自定義通知樣式,如果沒有設定預設為0
		notification.put("notification_basic_style", 4);	//只有notification_builder_id為0時才有效,才需要設定,
		notification.put("open_type", 2);			//點選通知後的行為(開啟Url:1; 自定義行為:2:其它值則預設開啟應用;)
		notification.put("pkg_content", "#Intent;launchFlags=0x10000000;"
					      + "component=com.gasj.cp/.ui.MessageInfoActivity;"
					      + "S.descrip="+messageContent+";"
					      + "B.ispush=true;S.title="+messageTitle+";end");			
		PushBatchUniMsgRequest request = new PushBatchUniMsgRequest()
					.addChannelIds(channelIds)			//頻道
					.addMsgExpires(new Integer(3600))		//設定訊息的有效時間,單位秒,預設3600*5.
					.addMessageType(1)				//通知型別 0 透傳,1通知
					.addMessage(notification.toString())
					.addDeviceType(3)				//客戶端型別 3,安卓 4 ios
					.addTopicId("BaiduPush");			// 設定類別主題			        
		// 5. 執行Http請求
		PushBatchUniMsgResponse response = pushClient.pushBatchUniMsg(request);		 
		// 6. Http請求返回值解析
		log.info(String.format("msgId: %s, sendTime: %d",response.getMsgId(), response.getSendTime()));
		result="已傳送";
	} catch (PushClientException e) {
		log.error(e.getMessage());
		result="傳送失敗";
	} catch (PushServerException e) {
		log.error(String.format("requestId: %d, errorCode: %d, errorMessage: %s",e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
		result="傳送失敗";
	}
	return result;
}