標籤:update app 顯示 front 控制 不必要 auth ace down
轉載請標明出處:http://blog.csdn.net/lmj623565791/article/details/27231237
如今app基本都有推送的功能。於是看了下百度雲的推送,官方文檔和Demo都非常到位,記錄下使用過程,目標是利用百度雲推送最為伺服器寫個及時通訊的範例~當然了。這是第一篇入門~
1、第一步就是在百度開發人員服務管理中建立項目。然後拿到API key , Secret Key ;這個過程就不多說了,上官網直接申請即可,不複雜。
2、下載雲推送的clientSDK。SDK的壓縮檔裡包括一個範例代碼,一個使用者手冊。和所需的libs和資源等(事實上直接看使用者手冊和Demo基本就沒問題了)。
3、準備工作結束,接下來,我們就直接開始建立項目測試
a、建立一個項目。然後把SDK中的libs中的jar和so目錄複寫到建立的項目中去
b、將manifest中的application的name設定為:com.baidu.frontia.FrontiaApplication
<application android:name="com.baidu.frontia.FrontiaApplication" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" >
假設你的項目須要自己定義Application,請參考使用者手冊中的相關配置。
c、增加許可權
<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.DISABLE_KEYGUARD" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
d、增加兩個receiver和一個Service(凝視標明了用處)
<!-- push service start --> <!-- 用於接收系統訊息以保證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" /> </intent-filter> </receiver> <!-- Push服務接收client發送的各種請求 --> <!-- 注意:RegistrationReceiver 在2.1.1及之前版本號碼有拼字失誤,為RegistratonReceiver ,用新版本號碼SDK時請更改為例如以下代碼 --> <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> <!-- Push 服務 --> <!-- 注意:在4.0 (包括)之後的版本號碼需加上例如以下所看到的的intent-filter action --> <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 service end -->
e、我們須要自己實現一個Receiver。來接收Push訊息、介面調用回調以及通知點擊事件。
<receiver android:name="com.example.zhy_baiduyun_tuisong01.receiver.MyPushMessageReceiver" > <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>
代碼:
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<String> sucessTags, List<String> 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<String> sucessTags, List<String> 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<String> 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 += "\n";// }// 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。
原始碼點擊下載
Android推送 百度雲推送 入門篇