百度雲推送

進入推送首頁文檔中心http://push.baidu.com/doc/android/api,根據文檔來設置。

開始

導入所需要的權限,jar包,so包等,eclipse可全部放在lib下,然而Android Studio則需要在src/main/下創建一個jniLibs文件夾來存放所有的so包。

設置完後,創建一個主類

package com.test.mypush;

import android.support.v7.app.ActionBarActivity;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PushManager.startWork(getApplicationContext(),PushConstants.LOGIN_TYPE_API_KEY,"ZCzREkMaQIXifUqtuXkL1hgN");
    }


}

在創建一個接收類(拷貝百度Demo中的代碼)

注意public void onNotificationClicked下的代碼,其中customJson = new JSONObject(customContentString);這一段代碼,這段代碼中的JSONObject是根據在推送消息下的高級設置下,添加字段得到的JSONObject的到的Value的值

package com.test.mypush;

import java.util.List;

import com.baidu.android.pushservice.PushMessageReceiver;

import java.text.SimpleDateFormat;
import java.util.Date;
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 android.widget.Toast;

import com.baidu.android.pushservice.PushMessageReceiver;

/*
 * Push消息處理receiver。請編寫您需要的回調函數, 一般來說: onBind是必須的,用來處理startWork返回值;
 *onMessage用來接收透傳消息; onSetTags、onDelTags、onListTags是tag相關操作的回調;
 *onNotificationClicked在通知被點擊時回調; onUnbind是stopWork接口的返回值回調

 * 返回值中的errorCode,解釋如下:
 *0 - Success
 *10001 - Network Problem
 *10101  Integrate Check Error
 *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 PushMsg extends PushMessageReceiver {
    /** TAG to Log */


    /**
     * 調用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.d(TAG, responseString);

        if (errorCode == 0) {
            // 綁定成功
        }
        // 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.d(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) {
            Toast.makeText(context, "123"+title+description, Toast.LENGTH_SHORT);
            try {
                JSONObject obj=new JSONObject(customContentString);
                String classname=obj.getString("startActivity");
                Intent intent=new Intent(context,Class.forName(context.getPackageName()+"."+classname));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

//        String notifyString = "通知點擊 title=\"" + title + "\" description=\""
//                + description + "\" customContent=" + customContentString;
//        Log.d(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);
    }

    /**
     * 接收通知到達的函數。
     *
     * @param context
     *            上下文
     * @param title
     *            推送的通知的標題
     * @param description
     *            推送的通知的描述
     * @param customContentString
     *            自定義內容,爲空或者json字符串
     */

    @Override
    public void onNotificationArrived(Context context, String title,
            String description, String customContentString) {

        String notifyString = "onNotificationArrived  title=\"" + title
                + "\" description=\"" + description + "\" customContent="
                + customContentString;
        Log.d(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更新界面展示代碼,應用請在這裏加入自己的處理邏輯
        // 你可以參考 onNotificationClicked中的提示從自定義內容獲取具體值
        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<String> sucessTags, List<String> failTags, String requestId) {
        String responseString = "onSetTags errorCode=" + errorCode
                + " sucessTags=" + sucessTags + " failTags=" + failTags
                + " requestId=" + requestId;
        Log.d(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<String> sucessTags, List<String> failTags, String requestId) {
        String responseString = "onDelTags errorCode=" + errorCode
                + " sucessTags=" + sucessTags + " failTags=" + failTags
                + " requestId=" + requestId;
        Log.d(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<String> tags,
            String requestId) {
        String responseString = "onListTags errorCode=" + errorCode + " tags="
                + tags;
        Log.d(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.d(TAG, responseString);

        if (errorCode == 0) {
            // 解綁定成功
        }
        // Demo更新界面展示代碼,應用請在這裏加入自己的處理邏輯
        updateContent(context, responseString);
    }

    private void updateContent(Context context, String content) {
        Log.d(TAG, "updateContent");
        String logText = "" + Utils.logStringCache;

        if (!logText.equals("")) {
            logText += "\n";
        }

        SimpleDateFormat sDateFormat = new SimpleDateFormat("HH-mm-ss");
        logText += sDateFormat.format(new Date()) + ": ";
        logText += content;

        Utils.logStringCache = logText;


    }

}

數據統計所用類

package com.test.mypush;

import com.baidu.mobstat.StatService;

import android.app.Activity;

public class BaseActivity extends Activity{
    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        StatService.onPause(this);
    }
    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        StatService.onResume(this);
    }
}

輔助類

package com.test.mypush;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.preference.PreferenceManager;

public class Utils {
    public static final String TAG = "PushDemoActivity";
    public static final String RESPONSE_METHOD = "method";
    public static final String RESPONSE_CONTENT = "content";
    public static final String RESPONSE_ERRCODE = "errcode";
    protected static final String ACTION_LOGIN = "com.baidu.pushdemo.action.LOGIN";
    public static final String ACTION_MESSAGE = "com.baiud.pushdemo.action.MESSAGE";
    public static final String ACTION_RESPONSE = "bccsclient.action.RESPONSE";
    public static final String ACTION_SHOW_MESSAGE = "bccsclient.action.SHOW_MESSAGE";
    protected static final String EXTRA_ACCESS_TOKEN = "access_token";
    public static final String EXTRA_MESSAGE = "message";

    public static String logStringCache = "";

    // 獲取ApiKey
    public static String getMetaValue(Context context, String metaKey) {
        Bundle metaData = null;
        String apiKey = null;
        if (context == null || metaKey == null) {
            return null;
        }
        try {
            ApplicationInfo ai = context.getPackageManager()
                    .getApplicationInfo(context.getPackageName(),
                            PackageManager.GET_META_DATA);
            if (null != ai) {
                metaData = ai.metaData;
            }
            if (null != metaData) {
                apiKey = metaData.getString(metaKey);
            }
        } catch (NameNotFoundException e) {

        }
        return apiKey;
    }

    public static List<String> getTagsList(String originalText) {
        if (originalText == null || originalText.equals("")) {
            return null;
        }
        List<String> tags = new ArrayList<String>();
        int indexOfComma = originalText.indexOf(',');
        String tag;
        while (indexOfComma != -1) {
            tag = originalText.substring(0, indexOfComma);
            tags.add(tag);

            originalText = originalText.substring(indexOfComma + 1);
            indexOfComma = originalText.indexOf(',');
        }

        tags.add(originalText);
        return tags;
    }

    public static String getLogText(Context context) {
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(context);
        return sp.getString("log_text", "");
    }

    public static void setLogText(Context context, String text) {
        SharedPreferences sp = PreferenceManager
                .getDefaultSharedPreferences(context);
        Editor editor = sp.edit();
        editor.putString("log_text", text);
        editor.commit();
    }

}

配置類

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.mypush"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
    <!-- Push service 運行需要的權限 -->
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.VIBRATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER" />
    <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
    <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- 用於接收系統消息以保證PushService正常運行 -->
        <receiver
            android:name="com.baidu.android.pushservice.PushServiceReceiver"
            android:process=":bdservice_v1" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="com.baidu.android.pushservice.action.notification.SHOW" />
                <action android:name="com.baidu.android.pushservice.action.media.CLICK" />
                <!-- 以下四項爲可選的action聲明,可大大提高service存活率和消息到達速度 -->
                <action android:name="android.intent.action.MEDIA_MOUNTED" />
                <action android:name="android.intent.action.USER_PRESENT" />
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
            </intent-filter>
        </receiver>
        <!-- Push服務接收客戶端發送的各種請求 -->
        <receiver
            android:name="com.baidu.android.pushservice.RegistrationReceiver"
            android:process=":bdservice_v1" >
            <intent-filter>
                <action android:name="com.baidu.android.pushservice.action.METHOD" />
                <action android:name="com.baidu.android.pushservice.action.BIND_SYNC" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.PACKAGE_REMOVED" />

                <data android:scheme="package" />
            </intent-filter>
        </receiver>

        <service
            android:name="com.baidu.android.pushservice.PushService"
            android:exported="true"
            android:process=":bdservice_v1" >
            <intent-filter>
                <action android:name="com.baidu.android.pushservice.action.PUSH_SERVICE" />
            </intent-filter>
        </service>
        <!-- 4.4版本新增的CommandService聲明,提升小米和魅族手機上的實際推送到達率 -->
        <service
            android:name="com.baidu.android.pushservice.CommandService"
            android:exported="true" />
        <!-- push結束 -->

        <receiver android:name=".PushMsg" >
            <intent-filter>

                <!-- 接收push消息 -->
                <action android:name="com.baidu.android.pushservice.action.MESSAGE" />
                <!-- 接收bind、setTags等method的返回結果 -->
                <action android:name="com.baidu.android.pushservice.action.RECEIVE" />
                <!-- 接收通知點擊事件,和通知自定義內容 -->
                <action android:name="com.baidu.android.pushservice.action.notification.CLICK" />
            </intent-filter>
        </receiver>

        <!-- 您從百度網站獲取的APP KEY -->
 <meta-data android:name="BaiduMobAd_STAT_ID" android:value="a58a0ddcb3"/> 
<!-- abcd1234 -->

<!-- 渠道商編號 -->
 <meta-data android:name="BaiduMobAd_CHANNEL" android:value="Baidu Market"/> 
<!-- 是否開啓錯誤日誌統計,默認爲false -->
 <meta-data android:name="BaiduMobAd_EXCEPTION_LOG" android:value="true"/> 
<!-- 日誌發送策略,可選值:APP_START、ONCE_A_DAY、SET_TIME_INTERVAL,默認爲APP_START -->
 <meta-data android:name="BaiduMobAd_SEND_STRATEGY" android:value="APP_START"/> 
<!-- 日誌發送策略 爲SET_TIME_INTERVAL時,需設定時間間隔(取消下行註釋)。取值爲1-24的整數,默認爲1 -->

<!-- <meta-data android:name="BaiduMobAd_TIME_INTERVAL" android:value="2" /> -->

<!-- 日誌僅在wifi網絡下發送,默認爲false -->
 <meta-data android:name="BaiduMobAd_ONLY_WIFI" android:value="false"/> 
<!-- 是否獲取基站位置信息 ,默認爲true -->
 <meta-data android:name="BaiduMobAd_CELL_LOCATION" android:value="true"/> 
<!-- 是否獲取GPS位置信息,默認爲true -->
 <meta-data android:name="BaiduMobAd_GPS_LOCATION" android:value="true"/> 
<!-- 是否獲取WIFI位置信息,默認爲true -->
 <meta-data android:name="BaiduMobAd_WIFI_LOCATION" android:value="true"/><meta-data
            android:name="api_key"
            android:value="ZCzREkMaQIXifUqtuXkL1hgN" />
    </application>

</manifest>

然後就可以在網頁推送消息了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章