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

來源:互聯網
上載者:User

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

協助文檔:http://developer.baidu.com/wiki/index.php?title=docs/cplat/push/api


我們先來看一下服務端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 {@Overrideprotected 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 = "大碗幹拌";@Overridepublic 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));}}}
運行結果:


Demo:http://download.csdn.net/detail/lxq_xsyu/6954373



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.