編輯:關於 Android 程式設計
做天氣 App 的第一步,是能把天氣網站的資料抓回來並解析成可用的結構。本文的範例會取得城市代碼對應的天氣資料,解析出溫度、風力、風向、未來幾天趨勢、當天狀況與圖示編號等資訊,並處理晝夜切換時的圖片對應,可以作為開發天氣預報應用的參考。
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.lmw.weather.MyApp;
import org.lmw.weather.entity.WeatherEntity;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
/**
* 解析天氣資料
*/
public class WeatherData {
private Activity activity;
private FinalHttp fh;
public static String def_weather_key = "def_weather";
public WeatherData(Activity activity) {
this.activity = activity;
fh = new FinalHttp();
fh.configTimeout(1000 * 3);
}
public void getData(final String cityId, final Handler hd) {
StringBuffer sb_url = new StringBuffer();
sb_url.append("https://0.qnweather.duapp.com/weather.php?uri=");
sb_url.append("https://m.weather.com.cn/data/");
sb_url.append(cityId);
sb_url.append(".html");
final Message msg = new Message();
fh.get(sb_url.toString(), new AjaxCallBack() {
@Override
public void onSuccess(Object t) {
super.onSuccess(t);
MySharedPreferences.writeMessage(activity, "def_weather", t.toString());
msg.what = 0;
msg.obj = parseJson(t.toString());
hd.sendMessage(msg);
}
@Override
public void onFailure(Throwable t, int errorNo, String strMsg) {
super.onFailure(t, errorNo, strMsg);
System.out.println("-------errorNo---------" + errorNo);
msg.what = -1;
msg.arg1 = errorNo;
// 請求失敗時改讀上次的快取
msg.obj = MySharedPreferences.readMessage(activity, def_weather_key, "");
hd.sendMessage(msg);
}
});
}
private String connServerForResult(String strUrl) {
// 建立 HttpGet 物件
HttpGet httpRequest = new HttpGet(strUrl);
String strResult = "";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpResponse httpResponse = httpClient.execute(httpRequest);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
strResult = EntityUtils.toString(httpResponse.getEntity());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("rresult" + strResult);
return strResult;
}
// 資料解析
private WeatherEntity parseJson(String strResult) {
WeatherEntity weather = null;
try {
JSONObject jsonObj = new JSONObject(strResult.replace("℃", "°"))
.getJSONObject("weatherinfo");
weather = new WeatherEntity();
int ftime = jsonObj.getInt("fchh"); // 更新時間(整點),用來判定 temp 屬於哪一天
int temp = 0; // 偏移量
if (ftime >= 18 || ftime < 8) {
weather.setNight(true);
temp = 1;
}
MyApp.week = jsonObj.getString("week"); // 今天星期幾
weather.setCity(jsonObj.getString("city")); // 城市
weather.setComfortable(jsonObj.getString("index")); // 舒適度
weather.setRefreshDate(getDate()); // 更新日期
weather.setRefreshTime(getTime()); // 更新時間
weather.setRefreshWeek(getWeek()); // 更新星期
weather.setPicIndex(jsonObj.getInt("img1")); // 當天天氣圖示編號
List<Integer> topPic = new ArrayList<Integer>(); // 高溫時段的圖示編號
if (temp == 1) {
topPic.add(getSavePic(activity));
} else {
topPic.add(getJsonPic(jsonObj, "img", 1 + temp));
savePic(activity, topPic.get(0));
}
topPic.add(getJsonPic(jsonObj, "img", 3 - temp));
topPic.add(getJsonPic(jsonObj, "img", 5 - temp));
topPic.add(getJsonPic(jsonObj, "img", 7 - temp));
weather.setTopPic(topPic);
List<Integer> lowPic = new ArrayList<Integer>(); // 低溫時段的圖示編號
lowPic.add(getJsonPic(jsonObj, "img", 2 - temp));
lowPic.add(getJsonPic(jsonObj, "img", 4 - temp));
lowPic.add(getJsonPic(jsonObj, "img", 6 - temp));
lowPic.add(getJsonPic(jsonObj, "img", 8 - temp));
weather.setLowPic(lowPic);
// 以上為圖示編號的取得邏輯
List<String> tempList = new ArrayList<String>(); // 未來五天溫度(第一筆是今天)
tempList.add(jsonObj.getString("temp1"));
tempList.add(jsonObj.getString("temp2"));
tempList.add(jsonObj.getString("temp3"));
tempList.add(jsonObj.getString("temp4"));
tempList.add(jsonObj.getString("temp5"));
tempList.add(jsonObj.getString("temp6"));
MyApp.tempList.clear();
MyApp.tempList = tempList;
List<String> weatherList = new ArrayList<String>(); // 未來五天天氣(第一筆是今天)
weatherList.add(jsonObj.getString("weather1"));
weatherList.add(jsonObj.getString("weather2"));
weatherList.add(jsonObj.getString("weather3"));
weatherList.add(jsonObj.getString("weather4"));
weatherList.add(jsonObj.getString("weather5"));
weatherList.add(jsonObj.getString("weather6"));
MyApp.weatherList.clear();
MyApp.weatherList = weatherList;
List<String> tempListMax = new ArrayList<String>(); // 未來五天最高溫(含 ° 符號)
if (temp == 1) {
tempListMax.add(getSaveTemperature(activity));
} else {
tempListMax.add(getTemperatureMaxAndMin(tempList.get(0))[0 + temp]);
saveTemperature(activity, tempListMax.get(0));
}
tempListMax.add(getTemperatureMaxAndMin(tempList.get(1 - temp))[0 + temp]);
tempListMax.add(getTemperatureMaxAndMin(tempList.get(2 - temp))[0 + temp]);
tempListMax.add(getTemperatureMaxAndMin(tempList.get(3 - temp))[0 + temp]);
weather.setTemperatureMax(tempListMax);
weather.setTodayTemperature(getTemperatureMaxAndMin(tempList.get(0))[0]); // 當天實時溫度
weather.setTodayWeather(jsonObj.getString("img_title1")); // 當天天氣描述
List<String> tempListMin = new ArrayList<String>(); // 未來四天最低溫(含 ° 符號)
tempListMin.add(getTemperatureMaxAndMin(tempList.get(0))[1 - temp]);
tempListMin.add(getTemperatureMaxAndMin(tempList.get(1))[1 - temp]);
tempListMin.add(getTemperatureMaxAndMin(tempList.get(2))[1 - temp]);
tempListMin.add(getTemperatureMaxAndMin(tempList.get(3))[1 - temp]);
weather.setTemperatureMin(tempListMin);
weather.setTomorrowTemperature(tempList.get(1)); // 明天溫度
if (temp == 1) {
weatherList.add(getSaveWeather(activity));
} else {
weatherList.add(jsonObj.getString("weather" + 1));
saveWeather(activity, weatherList.get(0));
}
weatherList.add(jsonObj.getString("weather" + (2 - temp)));
weatherList.add(jsonObj.getString("weather" + (3 - temp)));
weatherList.add(jsonObj.getString("weather" + (4 - temp)));
weather.setWeather(weatherList);
weather.setTomorrowWeather(weatherList.get(1));
List<String> windList = new ArrayList<String>(); // 未來四天風力
windList.add(jsonObj.getString("wind1"));
windList.add(jsonObj.getString("wind2"));
windList.add(jsonObj.getString("wind3"));
windList.add(jsonObj.getString("wind4"));
weather.setWind(windList);
weather.setMaxlist(transplate(tempListMax)); // 未來四天最高溫(無 ° 符號)
weather.setMinlist(transplate(tempListMin)); // 未來四天最低溫(無 ° 符號)
} catch (JSONException e) {
e.printStackTrace();
}
return weather;
}
// 更新日期,轉為「X月X日 周X」
private String getDate() {
SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 EEE", Locale.CHINA);
String date = sdf.format(new java.util.Date());
System.out.println(date);
return date;
}
// 更新時間,轉為「時:分 更新」
private String getTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.CHINA);
String time = sdf.format(new java.util.Date()) + " " + "更新";
System.out.println(time);
return time;
}
private String getWeek() {
return null;
}
// 取得最高溫與最低溫(含 ° 符號)
private String[] getTemperatureMaxAndMin(String str) {
return str.split("~");
}
// 去掉溫度中的 ° 符號
private List<Integer> transplate(List<String> strList) {
List<Integer> intList = new ArrayList<Integer>();
for (String temp : strList) {
intList.add(Integer.valueOf(temp.split("°")[0]));
}
return intList;
}
// 取得圖示編號,例如 "img" + "1"
private int getJsonPic(JSONObject jsonObj, String str, int index) throws JSONException {
int result = jsonObj.getInt(str + index);
if (result == 99 && index > 1) {
index--;
result = jsonObj.getInt(str + index);
}
return result;
}
private void saveTemperature(Activity activity, String value) {
// 可改寫入 SharedPreferences
}
private String getSaveTemperature(Activity activity) {
return MySharedPreferences.readMessage(activity, "temperature", "100");
}
private void saveWeather(Activity activity, String value) {
}
private String getSaveWeather(Activity activity) {
return MySharedPreferences.readMessage(activity, "weather", "");
}
private void savePic(Activity activity, int value) {
}
private int getSavePic(Activity activity) {
return MySharedPreferences.readMessage(activity, "pic", 99);
}
}
第一是晝夜偏移的處理。天氣資料源以整點更新的時間 (fchh) 標示資料屬於哪一天,18 點到隔天 8 點之間視為夜間,此時要將各項索引加一偏移,並改讀本地快取中的上一次數值,避免夜間抓到的是隔天資料。這個 temp 變數貫穿整段解析邏輯,是整份程式最關鍵的設計。
第二是快取回退機制。網路請求失敗時 (onFailure) 並不是直接顯示錯誤,而是改讀 SharedPreferences 中保存的上一筆資料,讓使用者至少還能看到稍早的天氣狀況,這個思路在行動應用中相當實用。
第三是單位正規化。資料源用「℃」而繪製時用「°」,因此在解析前先做一次字串替換,後續就不用處處判斷。
實作上仍有改進空間:org.apache.http 系列 API 在 Android 6.0 之後已被移除,新專案請改用 HttpURLConnection 或 OkHttp;另外 getWeek() 目前回傳 null,可以自行補上星期運算。
希望本文實例對你的 Android 天氣預報開發能有所幫助。
Delphi XE Android 開發筆記:環境設定、感測器、Intent 與常用元件
使用 Delphi XE 系列開發 Android 時,除了 Object Pascal 語法外,也需要熟悉 SDK/NDK 設定、應用程式啟動畫面、檔案部署、感測器、I
OpenGL ES 2.0 for Android:用三角形扇畫出正圓與寬高比修正
用三角形扇畫圓OpenGL ES 沒有直接畫圓的指令,但可以把它視為許多三角形組成的扇形。每一個三角形都以圓心為共同頂點,外圈則是圓周上的點。當分割數量足夠多,視覺上就會
Android 側滑菜單實作教學:動畫封裝與 FlipperLayout 完整解析
想在自己的 App 裡加入流暢順手的側滑菜單嗎?本文參考社群中廣為流傳的經典寫法,一步步帶你打造出具備 Path 風格彈出動畫的側滑選單。整個方案的靈魂在於一個名為 Ug
Android 對話框圓角實作:用 shape 拆分標題欄與內容區
剛接手公司的 Android 專案,設計稿丟來的需求是這樣: 彈出視窗四角要圓角,標題欄顏色與下方內容區不同,中間還要用藍色線分隔。 基本思路:shape + corn