Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> 百度雲推送集成在項目中集成

百度雲推送集成在項目中集成

編輯:關於Android編程

首先在權限中加入以下權限(API_KEY必須改,log日志可能打印不出來,只要到達數為1,等會就好了)

 


    
    
    
    
    
    
    
    
    
    
    
    
    
    

在主程序入口Application中

 

 


        
        
        
        
        


        
        
            

                
                
                
                
                
            
        

        
        
            
                
                
                
                
                
                
                
                
                
            
        
        
            
                
                
            
            
                

                
            
        

        
            
                
            
        
        

        
        
在Application中

 

 

public class Application extends android.app.Application {
	@Override
	public void onCreate() {
		super.onCreate();
		initPush();
	}

	private void initPush() {
		Resources resource = this.getResources();
		String pkgName = this.getPackageName();
		PushManager.startWork(getApplicationContext(),
				PushConstants.LOGIN_TYPE_API_KEY,
				Utils.getMetaValue(this, "api_key"));
		// Push: 如果想基於地理位置推送,可以打開支持地理位置的推送的開關
		// PushManager.enableLbs(getApplicationContext());

		// Push: 設置自定義的通知樣式,具體API介紹見用戶手冊,如果想使用系統默認的可以不加這段代碼
		// 請在通知推送界面中,高級設置->通知欄樣式->自定義樣式,選中並且填寫值:1,
		// 與下方代碼中 PushManager.setNotificationBuilder(this, 1, cBuilder)中的第二個參數對應
		CustomPushNotificationBuilder cBuilder = new CustomPushNotificationBuilder(
				resource.getIdentifier("notification_custom_builder", "layout",
						pkgName), resource.getIdentifier("notification_icon",
						"id", pkgName), resource.getIdentifier(
						"notification_title", "id", pkgName),
				resource.getIdentifier("notification_text", "id", pkgName));
		cBuilder.setNotificationFlags(Notification.FLAG_AUTO_CANCEL);
		cBuilder.setNotificationDefaults(Notification.DEFAULT_VIBRATE);
		cBuilder.setStatusbarIcon(this.getApplicationInfo().icon);
		cBuilder.setLayoutDrawable(resource.getIdentifier(
				"simple_notification_icon", "drawable", pkgName));
		cBuilder.setNotificationSound(Uri.withAppendedPath(
				Audio.Media.INTERNAL_CONTENT_URI, "6").toString());
		// 推送高級設置,通知欄樣式設置為下面的ID
		PushManager.setNotificationBuilder(this, 1, cBuilder);
	}

MyPushMessageReceiver中

 

 

package com.example.ykdemo;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.baidu.android.pushservice.PushMessageReceiver;


import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;

/*
 * Push娑堟伅澶勭悊receiver銆傝缂栧啓鎮ㄩ渶瑕佺殑鍥炶皟鍑芥暟锛?涓?埇鏉ヨ锛?onBind鏄繀椤葷殑锛岀敤鏉ュ鐞唖tartWork杩斿洖鍊硷紱
 *onMessage鐢ㄦ潵鎺ユ敹閫忎紶娑堟伅锛?onSetTags銆乷nDelTags銆乷nListTags鏄痶ag鐩稿叧鎿嶄綔鐨勫洖璋冿紱
 *onNotificationClicked鍦ㄩ?鐭ヨ鐐瑰嚮鏃跺洖璋冿紱 onUnbind鏄痵topWork鎺ュ彛鐨勮繑鍥炲?鍥炶皟
 * 杩斿洖鍊間腑鐨別rrorCode锛岃В閲婂涓嬶細
 *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
 * 褰撴偍閬囧埌浠ヤ笂杩斿洖閿欒鏃訛紝濡傛灉瑙i噴涓嶄簡鎮ㄧ殑闂锛岃鐢ㄥ悓涓?姹傜殑杩斿洖鍊紃equestId鍜宔rrorCode鑱旂郴鎴戜滑杩芥煡闂銆? *
 */

public class MyPushMessageReceiver extends PushMessageReceiver {
    /** TAG to Log */
    public static final String TAG = MyPushMessageReceiver.class
            .getSimpleName();

    /**
     * 璋冪敤PushManager.startWork鍚庯紝sdk灏嗗push
     * server鍙戣搗缁戝畾璇鋒眰锛岃繖涓繃绋嬫槸寮傛鐨勩?缁戝畾璇鋒眰鐨勭粨鏋滈?杩噊nBind杩斿洖銆?濡傛灉鎮ㄩ渶瑕佺敤鍗曟挱鎺ㄩ?锛岄渶瑕佹妸杩欓噷鑾峰彇鐨刢hannel
     * id鍜寀ser id涓婁紶鍒板簲鐢╯erver涓紝鍐嶈皟鐢╯erver鎺ュ彛鐢╟hannel id鍜寀ser id缁欏崟涓墜鏈烘垨鑰呯敤鎴鋒帹閫併?
     *
     * @param context
     *            BroadcastReceiver鐨勬墽琛孋ontext
     * @param errorCode
     *            缁戝畾鎺ュ彛杩斿洖鍊硷紝0 - 鎴愬姛
     * @param appid
     *            搴旂敤id銆俥rrorCode闈?鏃朵負null
     * @param userId
     *            搴旂敤user id銆俥rrorCode闈?鏃朵負null
     * @param channelId
     *            搴旂敤channel id銆俥rrorCode闈?鏃朵負null
     * @param requestId
     *            鍚戞湇鍔$鍙戣搗鐨勮姹俰d銆傚湪杩芥煡闂鏃舵湁鐢紱
     * @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) {
            // 缁戝畾鎴愬姛
            Log.d(TAG, "缁戝畾鎴愬姛");
        }
        // Demo鏇存柊鐣岄潰灞曠ず浠g爜锛屽簲鐢ㄨ鍦ㄨ繖閲屽姞鍏ヨ嚜宸辯殑澶勭悊閫昏緫
        updateContent(context, responseString);
    }

    /**
     * 鎺ユ敹閫忎紶娑堟伅鐨勫嚱鏁般?
     *
     * @param context
     *            涓婁笅鏂?     * @param message
     *            鎺ㄩ?鐨勬秷鎭?     * @param customContentString
     *            鑷畾涔夊唴瀹?涓虹┖鎴栬?json瀛楃涓?     */
    @Override
    public void onMessage(Context context, String message,
            String customContentString) {
        String messageString = "閫忎紶娑堟伅 onMessage=\"" + message
                + "\" customContentString=" + customContentString;
        Log.d(TAG, messageString);

        // 鑷畾涔夊唴瀹硅幏鍙栨柟寮忥紝mykey鍜宮yvalue瀵瑰簲閫忎紶娑堟伅鎺ㄩ?鏃惰嚜瀹氫箟鍐呭涓缃殑閿拰鍊?        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鏇存柊鐣岄潰灞曠ず浠g爜锛屽簲鐢ㄨ鍦ㄨ繖閲屽姞鍏ヨ嚜宸辯殑澶勭悊閫昏緫
//        updateContent(context, messageString);
//    }

    /**
     * 鎺ユ敹閫氱煡鍒拌揪鐨勫嚱鏁般?
     *
     * @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鍜宮yvalue瀵瑰簲閫氱煡鎺ㄩ?鏃惰嚜瀹氫箟鍐呭涓缃殑閿拰鍊?        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鏇存柊鐣岄潰灞曠ず浠g爜锛屽簲鐢ㄨ鍦ㄨ繖閲屽姞鍏ヨ嚜宸辯殑澶勭悊閫昏緫
        // 浣犲彲浠ュ弮鑰?onNotificationClicked涓殑鎻愮ず浠庤嚜瀹氫箟鍐呭鑾峰彇鍏蜂綋鍊?        updateContent(context, notifyString);
//    }

    /**
     * 鎺ユ敹閫氱煡鐐瑰嚮鐨勫嚱鏁般?
     *
     * @param context
     *            涓婁笅鏂?     * @param title
     *            鎺ㄩ?鐨勯?鐭ョ殑鏍囬
     * @param description
     *            鎺ㄩ?鐨勯?鐭ョ殑鎻忚堪
     * @param customContentString
     *            鑷畾涔夊唴瀹癸紝涓虹┖鎴栬?json瀛楃涓?     */
    @Override
    public void onNotificationClicked(Context context, String title,
            String description, String customContentString) {
        String notifyString = "閫氱煡鐐瑰嚮 onNotificationClicked title=\"" + title + "\" description=\""
                + description + "\" customContent=" + customContentString;
        Log.d(TAG, notifyString);

        // 鑷畾涔夊唴瀹硅幏鍙栨柟寮忥紝mykey鍜宮yvalue瀵瑰簲閫氱煡鎺ㄩ?鏃惰嚜瀹氫箟鍐呭涓缃殑閿拰鍊?        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鏇存柊鐣岄潰灞曠ず浠g爜锛屽簲鐢ㄨ鍦ㄨ繖閲屽姞鍏ヨ嚜宸辯殑澶勭悊閫昏緫
//        updateContent(context, notifyString);
//    }    
    
    /**
     * setTags() 鐨勫洖璋冨嚱鏁般?
     *
     * @param context
     *            涓婁笅鏂?     * @param errorCode
     *            閿欒鐮併?0琛ㄧず鏌愪簺tag宸茬粡璁劇疆鎴愬姛锛涢潪0琛ㄧず鎵?湁tag鐨勮缃潎澶辮觸銆?     * @param successTags
     *            璁劇疆鎴愬姛鐨則ag
     * @param failTags
     *            璁劇疆澶辮觸鐨則ag
     * @param requestId
     *            鍒嗛厤缁欏浜戞帹閫佺殑璇鋒眰鐨刬d
     */
    @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.d(TAG, responseString);

        // Demo鏇存柊鐣岄潰灞曠ず浠g爜锛屽簲鐢ㄨ鍦ㄨ繖閲屽姞鍏ヨ嚜宸辯殑澶勭悊閫昏緫
        updateContent(context, responseString);
    }

    /**
     * delTags() 鐨勫洖璋冨嚱鏁般?
     *
     * @param context
     *            涓婁笅鏂?     * @param errorCode
     *            閿欒鐮併?0琛ㄧず鏌愪簺tag宸茬粡鍒犻櫎鎴愬姛锛涢潪0琛ㄧず鎵?湁tag鍧囧垹闄ゅけ璐ャ?
     * @param successTags
     *            鎴愬姛鍒犻櫎鐨則ag
     * @param failTags
     *            鍒犻櫎澶辮觸鐨則ag
     * @param requestId
     *            鍒嗛厤缁欏浜戞帹閫佺殑璇鋒眰鐨刬d
     */
    @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.d(TAG, responseString);

        // Demo鏇存柊鐣岄潰灞曠ず浠g爜锛屽簲鐢ㄨ鍦ㄨ繖閲屽姞鍏ヨ嚜宸辯殑澶勭悊閫昏緫
        updateContent(context, responseString);
    }

    /**
     * listTags() 鐨勫洖璋冨嚱鏁般?
     *
     * @param context
     *            涓婁笅鏂?     * @param errorCode
     *            閿欒鐮併?0琛ㄧず鍒椾婦tag鎴愬姛锛涢潪0琛ㄧず澶辮觸銆?     * @param tags
     *            褰撳墠搴旂敤璁劇疆鐨勬墍鏈塼ag銆?     * @param requestId
     *            鍒嗛厤缁欏浜戞帹閫佺殑璇鋒眰鐨刬d
     */
    @Override
    public void onListTags(Context context, int errorCode, List tags,
            String requestId) {
        String responseString = "onListTags errorCode=" + errorCode + " tags="
                + tags;
        Log.d(TAG, responseString);

        // Demo鏇存柊鐣岄潰灞曠ず浠g爜锛屽簲鐢ㄨ鍦ㄨ繖閲屽姞鍏ヨ嚜宸辯殑澶勭悊閫昏緫
        updateContent(context, responseString);
    }

    /**
     * PushManager.stopWork() 鐨勫洖璋冨嚱鏁般?
     *
     * @param context
     *            涓婁笅鏂?     * @param errorCode
     *            閿欒鐮併?0琛ㄧず浠庝簯鎺ㄩ?瑙g粦瀹氭垚鍔燂紱闈?琛ㄧず澶辮觸銆?     * @param requestId
     *            鍒嗛厤缁欏浜戞帹閫佺殑璇鋒眰鐨刬d
     */
    @Override
    public void onUnbind(Context context, int errorCode, String requestId) {
        String responseString = "onUnbind errorCode=" + errorCode
                + " requestId = " + requestId;
        Log.d(TAG, responseString);

        if (errorCode == 0) {
            // 瑙g粦瀹氭垚鍔?            Log.d(TAG, "瑙g粦鎴愬姛");
        }
        // Demo鏇存柊鐣岄潰灞曠ず浠g爜锛屽簲鐢ㄨ鍦ㄨ繖閲屽姞鍏ヨ嚜宸辯殑澶勭悊閫昏緫
        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;

        Intent intent = new Intent();
        intent.setClass(context.getApplicationContext(), MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.getApplicationContext().startActivity(intent);
    }

}
Utils中
package com.example.ykdemo;


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;
import android.util.Log;

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) {
            Log.e(TAG, "error " + e.getMessage());
        }
        return apiKey;
    }

    public static List getTagsList(String originalText) {
        if (originalText == null || originalText.equals("")) {
            return null;
        }
        List tags = new ArrayList();
        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();
    }

}



 

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved