Utils 工具 推送
生活随笔
收集整理的這篇文章主要介紹了
Utils 工具 推送
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
work_weipa_百度云推送
2014-09-05 17:55 7人閱讀 評(píng)論(0) 收藏 舉報(bào)問題:怎么實(shí)現(xiàn)消息推送?
回答:下載sdk,根據(jù)文檔操作即可
資料:http://developer.baidu.com/wiki/index.php?title=docs/cplat/push/sdk/clientsdk看文檔和sdk(客戶端+服務(wù)端)
例子:
導(dǎo)包:
配置:
AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.weipa" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="7" android:targetSdkVersion="17"/> <!-- Push service 運(yùn)行需要的權(quán)限 --> <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:name="com.baidu.push.example.DemoApplication" android:icon="@drawable/ic_launcher" android:label="@string/app_name"> <activity android:name="com.baidu.push.example.PushDemoActivity" android:launchMode="singleTask" android:screenOrientation="portrait" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.baidu.push.example.LoginActivity" android:configChanges="orientation|keyboardHidden" android:label="@string/login" > </activity> <activity android:name="com.baidu.push.example.CustomActivity" android:launchMode="singleTask" android:configChanges="orientation|keyboardHidden" > </activity> <!-- push富媒體,不使用富媒體推送不需要 --> <activity android:name="com.baidu.android.pushservice.richmedia.MediaViewActivity" android:configChanges="orientation|keyboardHidden" android:label="MediaViewActivity" > </activity> <activity android:name="com.baidu.android.pushservice.richmedia.MediaListActivity" android:configChanges="orientation|keyboardHidden" android:label="MediaListActivity" android:launchMode="singleTask" > </activity> <!-- push富媒體結(jié)束 --> <!-- push應(yīng)用定義消息receiver聲明 --> <receiver android:name="你的包名.MyPushMessageReceiver"> <intent-filter> <!-- 接收push消息 --> <action android:name="com.baidu.android.pushservice.action.MESSAGE" /> <!-- 接收bind,unbind,fetch,delete等反饋消息 --> <action android:name="com.baidu.android.pushservice.action.RECEIVE" /> <action android:name="com.baidu.android.pushservice.action.notification.CLICK" /> </intent-filter> </receiver> <!-- push必須的receviver和service聲明 --> <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" /> </intent-filter> </receiver> <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> <!-- push結(jié)束 --> <!-- 在百度開發(fā)者中心查詢應(yīng)用的API Key --> <meta-data android:name="api_key" android:value="URzcY5unGHBQb8o8fLS1wGHu" /> </application> </manifest> View Code?
MyPushMessageReceiver.java import com.baidu.frontia.api.FrontiaPushMessageReceiver; /** * Push消息處理receiver。請(qǐng)編寫您需要的回調(diào)函數(shù), 一般來說: onBind是必須的,用來處理startWork返回值; * onMessage用來接收透?jìng)飨?#xff1b; onSetTags、onDelTags、onListTags是tag相關(guān)操作的回調(diào); * onNotificationClicked在通知被點(diǎn)擊時(shí)回調(diào); onUnbind是stopWork接口的返回值回調(diào) * * 返回值中的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 * * 當(dāng)您遇到以上返回錯(cuò)誤時(shí),如果解釋不了您的問題,請(qǐng)用同一請(qǐng)求的返回值requestId和errorCode聯(lián)系我們追查問題。 * */ public class MyPushMessageReceiver extends FrontiaPushMessageReceiver { /** TAG to Log */ public static final String TAG = MyPushMessageReceiver.class .getSimpleName(); /** * 調(diào)用PushManager.startWork后,sdk將對(duì)push * server發(fā)起綁定請(qǐng)求,這個(gè)過程是異步的。綁定請(qǐng)求的結(jié)果通過onBind返回。 如果您需要用單播推送,需要把這里獲取的channel * id和user id上傳到應(yīng)用server中,再調(diào)用server接口用channel id和user id給單個(gè)手機(jī)或者用戶推送。 * * @param context * BroadcastReceiver的執(zhí)行Context * @param errorCode * 綁定接口返回值,0 - 成功 * @param appid * 應(yīng)用id。errorCode非0時(shí)為null * @param userId * 應(yīng)用user id。errorCode非0時(shí)為null * @param channelId * 應(yīng)用channel id。errorCode非0時(shí)為null * @param requestId * 向服務(wù)端發(fā)起的請(qǐng)求id。在追查問題時(shí)有用; * @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); // 綁定成功,設(shè)置已綁定flag,可以有效的減少不必要的綁定請(qǐng)求 if (errorCode == 0) { Utils.setBind(context, true); } // Demo更新界面展示代碼,應(yīng)用請(qǐng)?jiān)谶@里加入自己的處理邏輯 updateContent(context, responseString); } /** * 接收透?jìng)飨⒌暮瘮?shù)。 * * @param context * 上下文 * @param message * 推送的消息 * @param customContentString * 自定義內(nèi)容,為空或者json字符串 */ @Override public void onMessage(Context context, String message, String customContentString) { String messageString = "透?jìng)飨?message=\"" + message + "\" customContentString=" + customContentString; Log.d(TAG, messageString); // 自定義內(nèi)容獲取方式,mykey和myvalue對(duì)應(yīng)透?jìng)飨⑼扑蜁r(shí)自定義內(nèi)容中設(shè)置的鍵和值 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更新界面展示代碼,應(yīng)用請(qǐng)?jiān)谶@里加入自己的處理邏輯 updateContent(context, messageString); } /** * 接收通知點(diǎn)擊的函數(shù)。注:推送通知被用戶點(diǎn)擊前,應(yīng)用無法通過接口獲取通知的內(nèi)容。 * * @param context * 上下文 * @param title * 推送的通知的標(biāo)題 * @param description * 推送的通知的描述 * @param customContentString * 自定義內(nèi)容,為空或者json字符串 */ @Override public void onNotificationClicked(Context context, String title, String description, String customContentString) { String notifyString = "通知點(diǎn)擊 title=\"" + title + "\" description=\"" + description + "\" customContent=" + customContentString; Log.d(TAG, notifyString); // 自定義內(nèi)容獲取方式,mykey和myvalue對(duì)應(yīng)通知推送時(shí)自定義內(nèi)容中設(shè)置的鍵和值 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更新界面展示代碼,應(yīng)用請(qǐng)?jiān)谶@里加入自己的處理邏輯 updateContent(context, notifyString); } /** * setTags() 的回調(diào)函數(shù)。 * * @param context * 上下文 * @param errorCode * 錯(cuò)誤碼。0表示某些tag已經(jīng)設(shè)置成功;非0表示所有tag的設(shè)置均失敗。 * @param successTags * 設(shè)置成功的tag * @param failTags * 設(shè)置失敗的tag * @param requestId * 分配給對(duì)云推送的請(qǐng)求的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更新界面展示代碼,應(yīng)用請(qǐng)?jiān)谶@里加入自己的處理邏輯 updateContent(context, responseString); } /** * delTags() 的回調(diào)函數(shù)。 * * @param context * 上下文 * @param errorCode * 錯(cuò)誤碼。0表示某些tag已經(jīng)刪除成功;非0表示所有tag均刪除失敗。 * @param successTags * 成功刪除的tag * @param failTags * 刪除失敗的tag * @param requestId * 分配給對(duì)云推送的請(qǐng)求的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更新界面展示代碼,應(yīng)用請(qǐng)?jiān)谶@里加入自己的處理邏輯 updateContent(context, responseString); } /** * listTags() 的回調(diào)函數(shù)。 * * @param context * 上下文 * @param errorCode * 錯(cuò)誤碼。0表示列舉tag成功;非0表示失敗。 * @param tags * 當(dāng)前應(yīng)用設(shè)置的所有tag。 * @param requestId * 分配給對(duì)云推送的請(qǐng)求的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更新界面展示代碼,應(yīng)用請(qǐng)?jiān)谶@里加入自己的處理邏輯 updateContent(context, responseString); } /** * PushManager.stopWork() 的回調(diào)函數(shù)。 * * @param context * 上下文 * @param errorCode * 錯(cuò)誤碼。0表示從云推送解綁定成功;非0表示失敗。 * @param requestId * 分配給對(duì)云推送的請(qǐng)求的id */ @Override public void onUnbind(Context context, int errorCode, String requestId) { String responseString = "onUnbind errorCode=" + errorCode + " requestId = " + requestId; Log.d(TAG, responseString); // 解綁定成功,設(shè)置未綁定flag, if (errorCode == 0) { Utils.setBind(context, false); } // Demo更新界面展示代碼,應(yīng)用請(qǐng)?jiān)谶@里加入自己的處理邏輯 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); } } View CodeUtils.java
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 = "";// 獲取ApiKeypublic 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;}// 用share preference來實(shí)現(xiàn)是否綁定的開關(guān)。在ionBind且成功時(shí)設(shè)置true,unBind且成功時(shí)設(shè)置falsepublic static boolean hasBind(Context context) {SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);String flag = sp.getString("bind_flag", "");if ("ok".equalsIgnoreCase(flag)) {return true;}return false;}public static void setBind(Context context, boolean flag) {String flagStr = "not";if (flag) {flagStr = "ok";}SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);Editor editor = sp.edit();editor.putString("bind_flag", flagStr);editor.commit();}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();}} View Code?
MainActivity.java
PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY, "URzcY5unGHBQb8o8fLS1wGHu"); View Code?
?
?
轉(zhuǎn)載于:https://www.cnblogs.com/qiuyang1/p/3964912.html
總結(jié)
以上是生活随笔為你收集整理的Utils 工具 推送的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: xml读取异常Invalid byte
- 下一篇: git 服务端搭建