Android推送 百度雲推送 入門篇
轉載請標明出處: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; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); autoBindBaiduYunTuiSong(); } private void initView() { mTextView = (TextView) findViewById(R.id.id_textview); } @Override protected 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推送 百度雲推送 入門篇