寫在前邊java
今天給你們推送一篇關於百度推送的文章。咱們手機上經常使用的 App 都會時不時的推送消息在咱們的消息欄顯示,經常使用的是QQ消息推送、微信消息推送、支付寶轉帳消息推送等。之後再作大大小小的項目都會用到推送,今天就總結了一篇用百度雲作推送消息,之後作項目會常常用到的,有時間就學習一下吧!android
用百度雲實現 App 通知推送json
步驟一:首先在百度雲註冊帳號(http://push.baidu.com/)微信
步驟二:註冊好帳號以後,建立應用併發
步驟三:點擊建立新應用。app
步驟四:填寫應用名稱。異步
步驟五:點擊建立好應用以後進行應用配置。ide
步驟六:選擇終端(這裏咱們選擇 Android),將項目包名填寫進去。函數
步驟七:要記住 API KEY 項目中要用到。學習
步驟八:下載百度推送 SDK(官網),添加到項目中。(公衆號回覆:百度SDK 便可獲取)
步驟九:開始新建 Android 項目爲 BaiDu_Push_Demo。
步驟十:在 build.gradle 中添加依賴。
1//加載jar包 2compile files('src/main/JniLibs/pushservice-6.1.1.21.jar')
步驟十一:新建 PushServiceReceiver.java 類(類中都是關於百度推送的回調)
1package com.example.boybaby.baidu_pust_demo; 2/** 3 * Created by apple on 2018/4/25. 4 */ 5import android.content.Context; 6import android.text.TextUtils; 7import android.util.Log; 8import android.widget.Toast; 9import org.json.JSONException; 10import org.json.JSONObject; 11import java.util.List; 12/* 13 * Push消息處理receiver。請編寫您須要的回調函數, 通常來講: onBind是必須的,用來處理startWork返回值; 14 *onMessage用來接收透傳消息; onSetTags、onDelTags、onListTags是tag相關操做的回調; 15 *onNotificationClicked在通知被點擊時回調; onUnbind是stopWork接口的返回值回調 16 * 返回值中的errorCode,解釋以下: 17 *0 - Success 18 *10001 - Network Problem 19 *10101 Integrate Check Error 20 *30600 - Internal Server Error 21 *30601 - Method Not Allowed 22 *30602 - Request Params Not Valid 23 *30603 - Authentication Failed 24 *30604 - Quota Use Up Payment Required 25 *30605 -Data Required Not Found 26 *30606 - Request Time Expires Timeout 27 *30607 - Channel Token Timeout 28 *30608 - Bind Relation Not Found 29 *30609 - Bind Number Too Many 30 * 當您遇到以上返回錯誤時,若是解釋不了您的問題,請用同一請求的返回值requestId和errorCode聯繫咱們追查問題。 31 * 32 */ 33public class PushMessageReceiver extends com.baidu.android.pushservice.PushMessageReceiver { 34 /** 35 * TAG to Log 36 */ 37 public static final String TAG = PushMessageReceiver.class 38 .getSimpleName(); 39 /** 40 * 調用PushManager.startWork後,sdk將對push 41 * server發起綁定請求,這個過程是異步的。綁定請求的結果經過onBind返回。 若是您須要用單播推送,須要把這裏獲取的channel 42 * id和user id上傳到應用server中,再調用server接口用channel id和user id給單個手機或者用戶推送。 43 * 44 * @param context BroadcastReceiver的執行Context 45 * @param errorCode 綁定接口返回值,0 - 成功 46 * @param appid 應用id。errorCode非0時爲null 47 * @param userId 應用user id。errorCode非0時爲null 48 * @param channelId 應用channel id。errorCode非0時爲null 49 * @param requestId 向服務端發起的請求id。在追查問題時有用; 50 * @return none 51 */ 52 @Override 53 public void onBind(Context context, int errorCode, String appid, 54 String userId, String channelId, String requestId) { 55 String responseString = "onBind errorCode=" + errorCode + " appid=" 56 + appid + " userId=" + userId + " channelId=" + channelId 57 + " requestId=" + requestId; 58 Log.d(TAG, responseString); 59 if (errorCode == 0) { 60 // 綁定成功 61 Log.d(TAG, "綁定成功"); 62 } 63 } 64 /** 65 * 接收透傳消息的函數。 66 * 67 * @param context 上下文 68 * @param message 推送的消息 69 * @param customContentString 自定義內容,爲空或者json字符串 70 */ 71 @Override 72 public void onMessage(Context context, String message, 73 String customContentString) { 74 String messageString = "透傳消息 onMessage=\"" + message 75 + "\" customContentString=" + customContentString; 76 Log.d(TAG, messageString); 77 // 自定義內容獲取方式,mykey和myvalue對應透傳消息推送時自定義內容中設置的鍵和值 78 if (!TextUtils.isEmpty(customContentString)) { 79 JSONObject customJson = null; 80 try { 81 customJson = new JSONObject(customContentString); 82 String myvalue = null; 83 if (!customJson.isNull("mykey")) { 84 myvalue = customJson.getString("mykey"); 85 } 86 } catch (JSONException e) { 87 // TODO Auto-generated catch block 88 e.printStackTrace(); 89 } 90 } 91 } 92 /** 93 * 接收通知到達的函數。 94 * 95 * @param context 上下文 96 * @param title 推送的通知的標題 97 * @param description 推送的通知的描述 98 * @param customContentString 自定義內容,爲空或者json字符串 99 */ 100 @Override 101 public void onNotificationArrived(Context context, String title, 102 String description, String customContentString) { 103 String notifyString = "通知到達 onNotificationArrived title=\"" + title 104 + "\" description=\"" + description + "\" customContent=" 105 + customContentString; 106 Log.d(TAG, notifyString); 107 //Toast.makeText(context,description,Toast.LENGTH_LONG).show(); 108 //Intent intent=new Intent(context,Main2Activity.class); 109 //context.startActivity(intent); 110 // 自定義內容獲取方式,mykey和myvalue對應通知推送時自定義內容中設置的鍵和值 111 if (!TextUtils.isEmpty(customContentString)) { 112 JSONObject customJson = null; 113 try { 114 customJson = new JSONObject(customContentString); 115 String myvalue = null; 116 if (!customJson.isNull("mykey")) { 117 myvalue = customJson.getString("mykey"); 118 } 119 } catch (JSONException e) { 120 // TODO Auto-generated catch block 121 e.printStackTrace(); 122 } 123 } 124 // Demo更新界面展現代碼,應用請在這裏加入本身的處理邏輯 125 // 你能夠參考 onNotificationClicked中的提示從自定義內容獲取具體值 126 } 127 /** 128 * 接收通知點擊的函數。 129 * 130 * @param context 上下文 131 * @param title 推送的通知的標題 132 * @param description 推送的通知的描述 133 * @param customContentString 自定義內容,爲空或者json字符串 134 */ 135 @Override 136 public void onNotificationClicked(Context context, String title, 137 String description, String customContentString) { 138 String notifyString = "通知點擊 onNotificationClicked title=\"" + title + "\" description=\"" 139 + description + "\" customContent=" + customContentString; 140 Log.d(TAG, notifyString); 141 Toast.makeText(context,description,Toast.LENGTH_LONG).show(); 142 // 自定義內容獲取方式,mykey和myvalue對應通知推送時自定義內容中設置的鍵和值 143 if (!TextUtils.isEmpty(customContentString)) { 144 JSONObject customJson = null; 145 try { 146 customJson = new JSONObject(customContentString); 147 String myvalue = null; 148 if (!customJson.isNull("mykey")) { 149 myvalue = customJson.getString("mykey"); 150 } 151 } catch (JSONException e) { 152 // TODO Auto-generated catch block 153 e.printStackTrace(); 154 } 155 } 156 } 157 /** 158 * setTags() 的回調函數。 159 * 160 * @param context 上下文 161 * @param errorCode 錯誤碼。0表示某些tag已經設置成功;非0表示全部tag的設置均失敗。 162 * @param failTags 設置失敗的tag 163 * @param requestId 分配給對雲推送的請求的id 164 */ 165 @Override 166 public void onSetTags(Context context, int errorCode, 167 List<String> sucessTags, List<String> failTags, String requestId) { 168 String responseString = "onSetTags errorCode=" + errorCode 169 + " sucessTags=" + sucessTags + " failTags=" + failTags 170 + " requestId=" + requestId; 171 Log.d(TAG, responseString); 172 } 173 /** 174 * delTags() 的回調函數。 175 * 176 * @param context 上下文 177 * @param errorCode 錯誤碼。0表示某些tag已經刪除成功;非0表示全部tag均刪除失敗。 178 * @param failTags 刪除失敗的tag 179 * @param requestId 分配給對雲推送的請求的id 180 */ 181 @Override 182 public void onDelTags(Context context, int errorCode, 183 List<String> sucessTags, List<String> failTags, String requestId) { 184 String responseString = "onDelTags errorCode=" + errorCode 185 + " sucessTags=" + sucessTags + " failTags=" + failTags 186 + " requestId=" + requestId; 187 Log.d(TAG, responseString); 188 } 189 /** 190 * listTags() 的回調函數。 191 * 192 * @param context 上下文 193 * @param errorCode 錯誤碼。0表示列舉tag成功;非0表示失敗。 194 * @param tags 當前應用設置的全部tag。 195 * @param requestId 分配給對雲推送的請求的id 196 */ 197 @Override 198 public void onListTags(Context context, int errorCode, List<String> tags, 199 String requestId) { 200 String responseString = "onListTags errorCode=" + errorCode + " tags=" 201 + tags; 202 Log.d(TAG, responseString); 203 } 204 /** 205 * PushManager.stopWork() 的回調函數。 206 * 207 * @param context 上下文 208 * @param errorCode 錯誤碼。0表示從雲推送解綁定成功;非0表示失敗。 209 * @param requestId 分配給對雲推送的請求的id 210 */ 211 @Override 212 public void onUnbind(Context context, int errorCode, String requestId) { 213 String responseString = "onUnbind errorCode=" + errorCode 214 + " requestId = " + requestId; 215 Log.d(TAG, responseString); 216 if (errorCode == 0) { 217 // 解綁定成功 218 Log.d(TAG, "解綁成功"); 219 } 220 } 221}
步驟十二:在 AndroidManifest.xml 中配置權限和相關服務。
1<?xml version="1.0" encoding="utf-8"?> 2<manifest xmlns:android="http://schemas.android.com/apk/res/android" 3 package="包名"> 4 <!-- Push service 運行須要的權限 --> 5 <uses-permission android:name="android.permission.INTERNET" /> 6 <uses-permission android:name="android.permission.READ_PHONE_STATE" /> 7 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 8 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> 9 <uses-permission android:name="android.permission.WRITE_SETTINGS" /> 10 <uses-permission android:name="android.permission.VIBRATE" /> 11 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 12 <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> 13 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 14 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> 15 <!-- 富媒體須要聲明的權限 --> 16 <uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER" /> 17 <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" /> 18 <uses-permission android:name="android.permission.EXPAND_STATUS_BAR" /> 19 <!-- 適配Android N系統必需的ContentProvider寫權限聲明,寫權限包含應用包名 --> 20 <uses-permission android:name="baidu.push.permission.WRITE_PUSHINFOPROVIDER.包名" /> 21 <permission 22 android:name="baidu.push.permission.WRITE_PUSHINFOPROVIDER.包名" 23 android:protectionLevel="signature"> 24 </permission> 25 <!-- 權限結束 --> 26 <application 27 android:allowBackup="true" 28 android:icon="@mipmap/ic_launcher" 29 android:label="@string/app_name" 30 android:roundIcon="@mipmap/ic_launcher_round" 31 android:supportsRtl="true" 32 android:theme="@style/AppTheme"> 33 <activity android:name=".MainActivity"> 34 <intent-filter> 35 <action android:name="android.intent.action.MAIN" /> 36 <category android:name="android.intent.category.LAUNCHER" /> 37 </intent-filter> 38 </activity> 39 <!-- push service start --> 40 <!-- 用於接收系統消息以保證PushService正常運行 --> 41 <receiver 42 android:name="com.baidu.android.pushservice.PushServiceReceiver" 43 android:process=":bdservice_v1"> 44 <intent-filter> 45 <action android:name="android.intent.action.BOOT_COMPLETED" /> 46 <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> 47 <action android:name="com.baidu.android.pushservice.action.notification.SHOW" /> 48 <action android:name="com.baidu.android.pushservice.action.media.CLICK" /> 49 <!-- 如下四項爲可選的action聲明,可大大提升service存活率和消息到達速度 --> 50 <action android:name="android.intent.action.MEDIA_MOUNTED" /> 51 <action android:name="android.intent.action.USER_PRESENT" /> 52 <action android:name="android.intent.action.ACTION_POWER_CONNECTED" /> 53 <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" /> 54 </intent-filter> 55 </receiver> 56 <!-- Push服務接收客戶端發送的各類請求 --> 57 <receiver 58 android:name="com.baidu.android.pushservice.RegistrationReceiver" 59 android:process=":bdservice_v1"> 60 <intent-filter> 61 <action android:name="com.baidu.android.pushservice.action.METHOD" /> 62 <action android:name="com.baidu.android.pushservice.action.BIND_SYNC" /> 63 </intent-filter> 64 <intent-filter> 65 <action android:name="android.intent.action.PACKAGE_REMOVED" /> 66 <data android:scheme="package" /> 67 </intent-filter> 68 </receiver> 69 <service 70 android:name="com.baidu.android.pushservice.PushService" 71 android:exported="true" 72 android:process=":bdservice_v1"> 73 <intent-filter> 74 <action android:name="com.baidu.android.pushservice.action.PUSH_SERVICE" /> 75 </intent-filter> 76 </service> 77 <!-- 4.4版本新增的CommandService聲明,提高小米和魅族手機上的實際推送到達率 --> 78 <service 79 android:name="com.baidu.android.pushservice.CommandService" 80 android:exported="true" /> 81 <!-- 適配Android N系統必需的ContentProvider聲明,寫權限包含應用包名 --> 82 <provider 83 android:name="com.baidu.android.pushservice.PushInfoProvider" 84 android:authorities="com.example.boybaby.baidu_pust_demo.bdpush" 85 android:exported="true" 86 android:protectionLevel="signature" 87 android:writePermission="baidu.push.permission.WRITE_PUSHINFOPROVIDER.包名.PushMessageReceiver" /> 88 <!-- push應用定義消息receiver聲明 --> 89 <receiver android:name="com.example.boybaby.baidu_pust_demo.PushMessageReceiver"> 90 <intent-filter> 91 <!-- 接收push消息 --> 92 <action android:name="com.baidu.android.pushservice.action.MESSAGE" /> 93 <!-- 接收bind、setTags等method的返回結果 --> 94 <action android:name="com.baidu.android.pushservice.action.RECEIVE" /> 95 <!-- 接收通知點擊事件,和通知自定義內容 --> 96 <action android:name="com.baidu.android.pushservice.action.notification.CLICK" /> 97 </intent-filter> 98 </receiver> 99 <!-- push結束 --> 100 </application> 101</manifest>
注意:包名必定要換成本身項目中的包名,不然推送消息接收不到
步驟十三:在 MainAcitivity 中註冊百度推送 API KEY。
1package com.example.boybaby.baidu_pust_demo; 2import android.os.Bundle; 3import android.support.v7.app.AppCompatActivity; 4import com.baidu.android.pushservice.PushConstants; 5import com.baidu.android.pushservice.PushManager; 6public class MainActivity extends AppCompatActivity { 7 @Override 8 protected void onCreate(Bundle savedInstanceState) { 9 super.onCreate(savedInstanceState); 10 setContentView(R.layout.activity_main); 11 //註冊,第三個參數是要修改的API KEY的字符串 12 PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY,"Cy1dU6vskzHqPmEmNu2aCZsR"); 13 } 14}
步驟十四:建立通知併發送。
步驟十五:發送成功。
手機端收到通知: