首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android 極光推送 (JPush) 接收透傳訊息並解析 JSON 完整指南

     編輯:程式設計疑難解答

場景說明

推送類型為「透傳訊息」,內容為 JSON 格式:{"cmd":"force_logout","token":"被擠掉的用戶令牌","msg":"具體提示信息"}。需在 BroadcastReceiver 中正確提取並解析。

核心步驟

  1. 在 onReceive 中獲取 Bundle 物件。
  2. 使用 JPushInterface.EXTRA_EXTRA 取得自訂欄位字串。
  3. 利用 JSONObject 解析 JSON,提取 cmd、token、msg 等欄位。

參考實作 (來自官方 Demo)

private static String printBundle(Bundle bundle) {
    StringBuilder sb = new StringBuilder();
    for (String key : bundle.keySet()) {
        if (key.equals(JPushInterface.EXTRA_EXTRA)) {
            if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                Log.i(TAG, "This message has no Extra data");
                continue;
            }
            try {
                JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                Iterator<String> it = json.keys();
                while (it.hasNext()) {
                    String myKey = it.next().toString();
                    sb.append("\nkey:" + key + ", value: [" + myKey + " - " + json.optString(myKey) + "]");
                }
            } catch (JSONException e) {
                Log.e(TAG, "Get message extra JSON error!");
            }
        } else {
            sb.append("\nkey:" + key + ", value:" + bundle.getString(key));
        }
    }
    return sb.toString();
}

注意事項

  • 確保在 AndroidManifest.xml 正確註冊 Receiver 並設定 android:exported="true"。
  • 透傳訊息不會自動顯示通知欄,需自行決定是否建立 Notification。
  • JSON 解析建議使用 optString 避免欄位缺失拋出異常。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved