Android推送 百度雲推送 入門篇

來源:互聯網
上載者:User

 

現在app基本都有推送的功能,於是看了下百度雲的推送,官方文檔和Demo都很到位,記錄下使用過程,目標是利用百度雲推送最為伺服器寫個及時通訊的例子~當然了,這是第一篇入門~

1、第一步就是在百度開發人員服務管理中建立項目,然後拿到API key , Secret Key ;這個過程就不多說了,上官網直接申請就行,不複雜。

2、下載雲推送的用戶端SDK,SDK的壓縮檔中包含一個例子代碼,一個使用者手冊,和所需的libs和資源等(其實直接看使用者手冊和Demo基本就沒問題了)。

3、準備工作結束,接下來,我們就直接開始建立項目測試

a、建立一個項目,然後把SDK中的libs中的jar和so檔案夾拷貝到建立的項目中去

b、將manifest中的application的name設定為:com.baidu.frontia.FrontiaApplication

 

   

如果你的項目需要自訂Application,請參考使用者手冊中的相關配置。

 

c、添加許可權

 

                                     

d、添加兩個receiver和一個Service(注釋標明了用處)

 

 

                                                                                                                                                                                                                                                                                                                                                 

e、我們需要自己實現一個Receiver,來接收Push訊息、介面調用回調以及通知點擊事件。

 

 

                                                                                                                           

代碼:

 

 

package com.example.zhy_baiduyun_tuisong01.receiver;import java.util.List;import org.json.JSONException;import org.json.JSONObject;import android.content.Context;import android.content.Intent;import android.text.TextUtils;import android.util.Log;import com.baidu.frontia.api.FrontiaPushMessageReceiver;import com.example.zhy_baiduyun_tuisong01.MainActivity;import com.example.zhy_baiduyun_tuisong01.util.PreUtils;/** * Push訊息處理receiver。請編寫您需要的回呼函數, 一般來說: onBind是必須的,用來處理startWork傳回值; * onMessage用來接收透傳訊息; onSetTags、onDelTags、onListTags是tag相關操作的回調; * onNotificationClicked在通知被點擊時回調; onUnbind是stopWork介面的傳回值回調 *  * 傳回值中的errorCode,解釋如下:  *  0 - Success *  10001 - Network Problem *  30600 - Internal Server Error *  30601 - Method Not Allowed  *  30602 - Request Params Not Valid *  30603 - Authentication Failed  *  30604 - Quota Use Up Payment Required  *  30605 - Data Required Not Found  *  30606 - Request Time Expires Timeout  *  30607 - Channel Token Timeout  *  30608 - Bind Relation Not Found  *  30609 - Bind Number Too Many *  * 當您遇到以上返回錯誤時,如果解釋不了您的問題,請用同一請求的傳回值requestId和errorCode聯絡我們追查問題。 *  */public class MyPushMessageReceiver extends FrontiaPushMessageReceiver {    /** TAG to Log */    public static final String TAG = MyPushMessageReceiver.class            .getSimpleName();    /**     * 調用PushManager.startWork後,sdk將對push     * server發起綁定請求,這個過程是非同步。綁定請求的結果通過onBind返回。 如果您需要用單播推送,需要把這裡擷取的channel     * id和user id上傳到應用server中,再調用server介面用channel id和user id給單個手機或者使用者推送。     *      * @param context     *            BroadcastReceiver的執行Context     * @param errorCode     *            綁定介面傳回值,0 - 成功     * @param appid     *            應用id。errorCode非0時為null     * @param userId     *            應用user id。errorCode非0時為null     * @param channelId     *            應用channel id。errorCode非0時為null     * @param requestId     *            向服務端發起的請求id。在追查問題時有用;     * @return none     */    @Override    public void onBind(Context context, int errorCode, String appid,            String userId, String channelId, String requestId) {        String responseString = onBind errorCode= + errorCode +  appid=                + appid +  userId= + userId +  channelId= + channelId                +  requestId= + requestId;        Log.e(TAG, responseString);        // 綁定成功,設定已綁定flag,可以有效減少不必要的綁定請求        if (errorCode == 0) {            PreUtils.bind(context);        }        // Demo更新介面展示代碼,應用請在這裡加入自己的處理邏輯        updateContent(context, responseString);    }    /**     * 接收透傳訊息的函數。     *      * @param context     *            上下文     * @param message     *            推送的訊息     * @param customContentString     *            自訂內容,為空白或者json字串     */    @Override    public void onMessage(Context context, String message,            String customContentString) {        String messageString = 透傳訊息 message= + message                +  customContentString= + customContentString;        Log.e(TAG, messageString);        // 自訂內容擷取方式,mykey和myvalue對應透傳訊息推送時自訂內容中設定的鍵和值        if (!TextUtils.isEmpty(customContentString)) {            JSONObject customJson = null;            try {                customJson = new JSONObject(customContentString);                String myvalue = null;                if (customJson.isNull(mykey)) {                    myvalue = customJson.getString(mykey);                }            } catch (JSONException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        // Demo更新介面展示代碼,應用請在這裡加入自己的處理邏輯        updateContent(context, messageString);    }            /**     * 接收通知點擊的函數。註:推播通知被使用者點擊前,應用無法通過介面擷取通知的內容。     *      * @param context     *            上下文     * @param title     *            推送的通知的標題     * @param description     *            推送的通知的描述     * @param customContentString     *            自訂內容,為空白或者json字串     */    @Override    public void onNotificationClicked(Context context, String title,            String description, String customContentString) {                String notifyString = 通知點擊 title= + title +  description=                + description +  customContent= + customContentString;        Log.e(TAG, notifyString);        // 自訂內容擷取方式,mykey和myvalue對應通知推送時自訂內容中設定的鍵和值        if (!TextUtils.isEmpty(customContentString)) {            JSONObject customJson = null;            try {                customJson = new JSONObject(customContentString);                String myvalue = null;                if (customJson.isNull(mykey)) {                    myvalue = customJson.getString(mykey);                }            } catch (JSONException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }        }        // Demo更新介面展示代碼,應用請在這裡加入自己的處理邏輯        updateContent(context, notifyString);    }    /**     * setTags() 的回呼函數。     *      * @param context     *            上下文     * @param errorCode     *            錯誤碼。0表示某些tag已經設定成功;非0表示所有tag的設定均失敗。     * @param successTags     *            設定成功的tag     * @param failTags     *            設定失敗的tag     * @param requestId     *            分配給對雲推送的請求的id     */    @Override    public void onSetTags(Context context, int errorCode,            List sucessTags, List failTags, String requestId) {        String responseString = onSetTags errorCode= + errorCode                +  sucessTags= + sucessTags +  failTags= + failTags                +  requestId= + requestId;        Log.e(TAG, responseString);        // Demo更新介面展示代碼,應用請在這裡加入自己的處理邏輯        updateContent(context, responseString);    }    /**     * delTags() 的回呼函數。     *      * @param context     *            上下文     * @param errorCode     *            錯誤碼。0表示某些tag已經刪除成功;非0表示所有tag均刪除失敗。     * @param successTags     *            成功刪除的tag     * @param failTags     *            刪除失敗的tag     * @param requestId     *            分配給對雲推送的請求的id     */    @Override    public void onDelTags(Context context, int errorCode,            List sucessTags, List failTags, String requestId) {        String responseString = onDelTags errorCode= + errorCode                +  sucessTags= + sucessTags +  failTags= + failTags                +  requestId= + requestId;        Log.e(TAG, responseString);        // Demo更新介面展示代碼,應用請在這裡加入自己的處理邏輯        updateContent(context, responseString);    }    /**     * listTags() 的回呼函數。     *      * @param context     *            上下文     * @param errorCode     *            錯誤碼。0表示列舉tag成功;非0表示失敗。     * @param tags     *            當前應用設定的所有tag。     * @param requestId     *            分配給對雲推送的請求的id     */    @Override    public void onListTags(Context context, int errorCode, List tags,            String requestId) {        String responseString = onListTags errorCode= + errorCode +  tags=                + tags;        Log.e(TAG, responseString);        // Demo更新介面展示代碼,應用請在這裡加入自己的處理邏輯        updateContent(context, responseString);    }    /**     * PushManager.stopWork() 的回呼函數。     *      * @param context     *            上下文     * @param errorCode     *            錯誤碼。0表示從雲推送解除綁定定成功;非0表示失敗。     * @param requestId     *            分配給對雲推送的請求的id     */    @Override    public void onUnbind(Context context, int errorCode, String requestId) {        String responseString = onUnbind errorCode= + errorCode                +  requestId =  + requestId;        Log.e(TAG, responseString);        // 解除綁定定成功,設定未綁定flag,        if (errorCode == 0) {            PreUtils.unbind(context);        }        // Demo更新介面展示代碼,應用請在這裡加入自己的處理邏輯        updateContent(context, responseString);    }    private void updateContent(Context context, String content) {        Log.e(TAG, updateContent);        //String logText =  + Utils.logStringCache;//        if (!logText.equals()) {//            logText += ;//        }//        SimpleDateFormat sDateFormat = new SimpleDateFormat(HH-mm-ss);//        logText += sDateFormat.format(new Date()) + : ;//        logText += content;        //Utils.logStringCache = logText;        Intent intent = new Intent();        intent.putExtra(result, content);        intent.setClass(context.getApplicationContext(), MainActivity.class);        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);        context.getApplicationContext().startActivity(intent);    }}

代碼是官方Demo的代碼,注釋特別詳細,做了一點修改,每次回調的結果,我會讓顯示到主介面上。主Actvity:

 

 

package com.example.zhy_baiduyun_tuisong01;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.util.Log;import android.widget.TextView;import com.baidu.android.pushservice.PushConstants;import com.baidu.android.pushservice.PushManager;import com.example.zhy_baiduyun_tuisong01.util.PreUtils;public class MainActivity extends Activity{private TextView mTextView;@Overrideprotected void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();autoBindBaiduYunTuiSong();}private void initView(){mTextView = (TextView) findViewById(R.id.id_textview);}@Overrideprotected void onNewIntent(Intent intent){String result = intent.getStringExtra(result);if (result != null){mTextView.setText(result);}// super.onNewIntent(intent);}/** * 如果沒有綁定百度雲,則綁定,並記錄在屬性檔案中 */private void autoBindBaiduYunTuiSong(){if (!PreUtils.isBind(getApplicationContext())){PushManager.startWork(getApplicationContext(),PushConstants.LOGIN_TYPE_API_KEY,TVkKGesssSDs5q7AamLGnNCs);}}}

最終的測試:

 

1、應用安裝後,如果綁定成功,主介面:

然後在管理主控台開始分別發送通知和訊息:

2、當發送通知並點擊通知:

3、當發送訊息:

 

 

好了,都是最基本的功能,沒什麼技術含量就是需要點耐心,下面貼上源碼,使用源碼請把MainActivity裡面的KEY設定成自己申請的KEY。

 

源碼點擊下載

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.