Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

從零打造 Android 天氣 App:網路連線、背景執行緒與 JSON 解析全流程

編輯:Android 開發實例

幾乎所有真實的 App 都要跟網路打交道,而「按下按鈕 → 發請求 → 拿 JSON → 解析 → 更新畫面」就是最典型的一條鏈路。本章用一個天氣查詢 App 把這條鏈路完整走一遍,並在過程中說明每個環節容易出錯的地方。

JSON(JavaScript Object Notation)之所以能取代 XML 成為主流,關鍵在於它精簡:沒有結束標籤、沒有屬性宣告,同一份資料的傳輸量與解析成本都低得多。Android 內建 JSONObject、JSONArray、JSONStringer、JSONTokenizer 四個類別來處理它。

先確認資料長相

我們要從回應中取出國家代碼與溫度:

 { "sys": { "country":"GB", "sunrise":1381107633, "sunset":1381149604 }, "weather":[ { "id":711, "main":"Smoke", "description":"smoke", "icon":"50n" } ], "main": { "temp":304.15, "pressure":1009, } }

四個基本元素

元素說明
Array []方括號是陣列,weather 屬於這一種。
Object {}大括號是物件,sys 與 main 都是。
Key物件中的鍵,一定是字串。
Value值可以是字串、整數、浮點數或布林。

解析:兩行就開始

把字串交給 JSONObject,再逐層取值:

 String in; JSONObject reader = new JSONObject(in);

JSONObject sys = reader.getJSONObject("sys"); country = sys.getString("country"); JSONObject main = reader.getJSONObject("main"); temperature = main.getString("temp");

getJSONObject() 往下鑽一層,getString() 取出指定鍵的字串值。若需要其他型別,還有 getInt()、getDouble()、getBoolean()、getLong()、length() 與 names() 等方法可用。

動手做:完整流程

步驟要做的事
1用 Android Studio 建立 JSONParser 專案,Target SDK 選新版。
2修改 MainActivity.java,加入 open() 事件。
3修改 activity_main.xml 加入五組標籤與輸入框、一顆查詢鈕。
4修改 res/values/string.xml 加入字串。
5新增 HandleJSON.java 處理連線與解析。
6在 AndroidManifest.xml 加上 INTERNET 權限。
7執行並驗證結果。

MainActivity.java:

 package com.example.jsonparser; import android.os.Bundle; import android.app.Activity; import android.view.View; import android.widget.EditText; public class MainActivity extends Activity { private String url1 = "https://api.openweathermap.org/data/2.5/weather?q="; private EditText location,country,temperature,humidity,pressure; private HandleJSON obj; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); location = (EditText)findViewById(R.id.editText1); country = (EditText)findViewById(R.id.editText2); temperature = (EditText)findViewById(R.id.editText3); humidity = (EditText)findViewById(R.id.editText4); pressure = (EditText)findViewById(R.id.editText5); } public void open(View view){ String finalUrl = url1 + location.getText().toString(); obj = new HandleJSON(finalUrl); obj.fetchJSON(); while(obj.parsingComplete); country.setText(obj.getCountry()); temperature.setText(obj.getTemperature()); humidity.setText(obj.getHumidity()); pressure.setText(obj.getPressure()); } }

HandleJSON.java 中,fetchJSON() 開一條新執行緒做連線,readAndParseJSON() 專心解析:

 package com.example.jsonparser; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import org.json.JSONObject; public class HandleJSON { private String country = "county"; private String temperature = "temperature"; private String humidity = "humidity"; private String pressure = "pressure"; private String urlString = null; public volatile boolean parsingComplete = true; public HandleJSON(String url){ this.urlString = url; } public String getCountry(){ return country; } public String getTemperature(){ return temperature; } public String getHumidity(){ return humidity; } public String getPressure(){ return pressure; } public void readAndParseJSON(String in) { try { JSONObject reader = new JSONObject(in); JSONObject sys = reader.getJSONObject("sys"); country = sys.getString("country"); JSONObject main = reader.getJSONObject("main"); temperature = main.getString("temp"); pressure = main.getString("pressure"); humidity = main.getString("humidity"); parsingComplete = false; } catch (Exception e) { e.printStackTrace(); } } public void fetchJSON(){ Thread thread = new Thread(new Runnable(){ @Override public void run() { try { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000); conn.setConnectTimeout(15000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); InputStream stream = conn.getInputStream(); String data = convertStreamToString(stream); readAndParseJSON(data); stream.close(); } catch (Exception e) { e.printStackTrace(); } } }); thread.start(); } static String convertStreamToString(java.io.InputStream is) { java.util.Scanner s = new java.util.Scanner(is).useDelimiter("A"); return s.hasNext() ? s.next() : ""; } }

activity_main.xml(省略純樣式屬性):

 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textV1" android:text="@string/location" /> <EditText android:id="@+id/editText1" android:layout_toRightOf="@id/textV1" /> <TextView android:id="@+id/textV2" android:text="@string/country" android:layout_below="@id/editText1" /> <EditText android:id="@+id/editText2" android:layout_below="@id/editText1" /> <TextView android:id="@+id/textV3" android:text="@string/temperature" android:layout_below="@id/editText2" /> <EditText android:id="@+id/editText3" android:layout_below="@id/editText2" /> <TextView android:id="@+id/textV4" android:text="@string/humidity" android:layout_below="@id/editText3" /> <EditText android:id="@+id/editText4" android:layout_below="@id/editText3" /> <TextView android:id="@+id/textV5" android:text="@string/pressure" android:layout_below="@id/editText4" /> <EditText android:id="@+id/editText5" android:layout_below="@id/editText4" /> <Button android:id="@+id/button1" android:onClick="open" android:text="@string/weather" /> </RelativeLayout>

string.xml 與 AndroidManifest.xml(務必加 INTERNET 權限):

 <resources> <string name="app_name">JSONParser</string> <string name="location">Location</string> <string name="country">Country:</string> <string name="temperature">Temperature:</string> <string name="humidity">Humidity:</string> <string name="pressure">Pressure:</string> <string name="weather">Weather</string> </resources>

<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.yiibai.jsonparser"> <uses-permission android:name="android.permission.INTERNET"/> <application android:label="@string/app_name"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>

執行結果

啟動 App 後畫面如下,五個欄位分別對應位置與四項氣象資料:

輸入城市名稱(範例為紐約)後按下查詢按鈕:

App 會連上服務、取回 JSON 並解析填表。最後三個提醒:回傳的溫度是開爾文,攝氏度請減 273.15;範例中的 while 迴圈只是為了教學等待,正式專案應改用非同步回呼或 LiveData 之類的機制,避免空轉消耗 CPU;此外 Android 不允許在主執行緒做網路連線,這也是為什麼範例一定要開新執行緒。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved