1. 程式人生 > >百度訊息推送SDK探究(並附上最簡推送Demo)

百度訊息推送SDK探究(並附上最簡推送Demo)

上一篇《百度訊息推送REST API探究》中瞭解瞭如何使用REST API推送訊息,這一篇我們來看一下百度訊息推送為我們提供的SDK.


我們先來看一下服務端SDK


下載解壓後的目錄結構


還是前面提到的那句話,先看sample

package test;

import com.baidu.yun.channel.auth.ChannelKeyPair;
import com.baidu.yun.channel.client.BaiduChannelClient;
import com.baidu.yun.channel.exception.ChannelClientException;
import com.baidu.yun.channel.exception.ChannelServerException;
import com.baidu.yun.channel.model.PushBroadcastMessageRequest;
import com.baidu.yun.channel.model.PushBroadcastMessageResponse;
import com.baidu.yun.channel.model.PushUnicastMessageRequest;
import com.baidu.yun.channel.model.PushUnicastMessageResponse;
import com.baidu.yun.core.log.YunLogEvent;
import com.baidu.yun.core.log.YunLogHandler;

public class AndroidPushNotificationSample {

    public static void main(String[] args) {

        /*
         * @brief 推送單播通知(Android Push SDK攔截並解析) message_type = 1 (預設為0)
         */

        // 1. 設定developer平臺的ApiKey/SecretKey
        String apiKey = "自己的apiKey";
        String secretKey = "自己的secretKey";
        ChannelKeyPair pair = new ChannelKeyPair(apiKey, secretKey);

        // 2. 建立BaiduChannelClient物件例項
        BaiduChannelClient channelClient = new BaiduChannelClient(pair);

        // 3. 若要了解互動細節,請註冊YunLogHandler類
        channelClient.setChannelLogHandler(new YunLogHandler() {
            @Override
            public void onHandle(YunLogEvent event) {
                System.out.println(event.getMessage());
            }
        });

        try {

            // 4. 建立請求類物件
            // 手機端的ChannelId, 手機端的UserId, 先用1111111111111代替,使用者需替換為自己的
        	PushBroadcastMessageRequest request = new PushBroadcastMessageRequest();
        	
            //PushUnicastMessageRequest request = new PushUnicastMessageRequest();
        	
        	
            request.setDeviceType(3); // device_type => 1: web 2: pc 3:android
                                      // 4:ios 5:wp
            //request.setChannelId(3721876992860457831L);
            //request.setUserId("1105477905904433716");

            request.setMessageType(1);
            request.setMessage("{\"title\":\"大碗幹拌\",\"description\":\"歡迎訪問大碗幹拌的CSDN部落格\"}");

            // 5. 呼叫pushMessage介面
           /* PushUnicastMessageResponse response = channelClient
                    .pushUnicastMessage(request);
                   
*/
            PushBroadcastMessageResponse response = channelClient.pushBroadcastMessage(request);
            
            // 6. 認證推送成功
            System.out.println("push amount : " + response.getSuccessAmount());

        } catch (ChannelClientException e) {
            // 處理客戶端錯誤異常
            e.printStackTrace();
        } catch (ChannelServerException e) {
            // 處理服務端錯誤異常
            System.out.println(String.format(
                    "request_id: %d, error_code: %d, error_message: %s",
                    e.getRequestId(), e.getErrorCode(), e.getErrorMsg()));
        }

    }

}
例子很簡單,從名字上就能看出作用,這裡就不囉嗦了。

下面我們來看看客戶端的SDK

下載Android端SDK後解壓如下

從使用者手冊中我們可以看到,Android Push服務以後臺service方式執行,如果某個手機中集成了多個百度推送服務,為了減少記憶體和和功耗,只有一個後臺service來共享Push通道。

接下來來看一下使用者手冊:

根據使用者手冊上的描述,我做了一個最簡Demo,這個demo完全可以滿足一般需求。


MainActivity.java

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 以apikey的方式登入,一般放在主Activity的onCreate中
		PushManager.startWork(getApplicationContext(),
				PushConstants.LOGIN_TYPE_API_KEY, "自己的apikey");
		
	}
}
PushReciver.java
package com.example.baidulotterypush;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.baidu.android.pushservice.PushConstants;

public class MyPushMessageReceiver extends BroadcastReceiver{

	private static final String TAG = "大碗幹拌";

	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(PushConstants.ACTION_MESSAGE)) {

		} else if (intent.getAction().equals(PushConstants.ACTION_RECEIVE)) {

		} else if (intent.getAction().equals(	
			PushConstants.ACTION_RECEIVER_NOTIFICATION_CLICK)) {
			Log.i(TAG, "title = " + intent.getStringExtra(PushConstants.EXTRA_NOTIFICATION_TITLE));
			Log.i(TAG, "content = " + intent.getStringExtra(PushConstants.EXTRA_NOTIFICATION_CONTENT));
		}
	}
}
執行結果: