編輯:關於 Android 程式設計
專案需求是在首頁展示當前天氣概況。挑選資料源的過程頗費心思:Google 的介面早已不可用,某些服務則因故不願採用,串接 WebService 又擔心手機端頻繁請求的穩定性與各種免費額度限制。最後選定中國天氣網(www.weather.com.cn),它由中國氣象局公共氣象服務中心維護,資料量大且穩定,足以應付一般應用的需求。
唯一的麻煩是:介面要求傳入城市代碼,而非城市名稱。
社群流傳的公開介面主要有三個(以深圳 101280601 為例):
① https://m.weather.com.cn/data/101280601.html——資訊最完整,回傳 JSON,包含 city、city_en、日期、星期、cityid、未來數日的 temp1~temp6 與華氏溫度、weather1~weather6、對應圖示編號 img1~img12,以及 index(穿衣指數)、index_uv(紫外線)、index_tr(旅遊)、index_co(舒適度)、index_cl(晨練)、index_ls(晾晒)、index_ag(空氣質量)等生活指標。
② https://www.weather.com.cn/data/sk/101280601.html——即時觀測,資訊簡潔:city、cityid、temp(目前氣溫)、WD(風向)、WS(風力)、SD(濕度)、time(觀測時間)。
③ https://www.weather.com.cn/data/cityinfo/101010100.html—— juga簡潔,回傳 temp1/temp2(低溫/高溫)、weather、img1/img2(夜間與日間圖示)、ptime。
三者都是 JSON,解析並不困難。
方法一:手動查詢。在官網搜尋框輸入城市,瀏覽器跳轉後的網址形如 https://www.weather.com.cn/weather/101280601.shtml,其中數字即為該城市的代碼。顯然只適合少量城市。
方法二:依 IP 反查。在行動端並不適用,精度也不足。
方法三(採用):本地對照表。把完整的城市代碼表放進應用程式內的 SQLite 資料庫,以城市名稱查出代碼,再拼接請求網址。這個做法離線可用、查詢極快,缺點是資料表需要定期更新。
在子線程中先查本地資料庫取得代碼,再發請求、解析 JSON,最後透過 Handler 回主線程更新 UI:
public void initWaetherData() {
new Thread(new Runnable() {
@Override
public void run() {
DBHelper helper = new DBHelper(getApplicationContext());
String cityName = "深圳";
String cityCode = null;
String sql = "select * from city_table where CITY = '" + cityName + "';";
Cursor cursor = helper.getReadableDatabase().rawQuery(sql, null);
if (cursor != null) {
cursor.moveToFirst();
cityCode = cursor.getString(cursor.getColumnIndex("WEATHER_ID"));
}
cursor.close();
helper.close();
String weatherUrl = "https://www.weather.com.cn/data/cityinfo/" + cityCode + ".html";
String weatherJson = queryStringForGet(weatherUrl);
try {
JSONObject jsonObject = new JSONObject(weatherJson);
JSONObject weatherObject = jsonObject.getJSONObject("weatherinfo");
Message message = new Message();
message.obj = weatherObject;
handler.sendMessage(message);
} catch (JSONException e) {
e.printStackTrace();
}
}
}).start();
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
JSONObject object = (JSONObject) msg.obj;
try {
txt_weather_city.setText(object.getString("city"));
txt_weather_temp.setText(object.getString("temp2") + "/" + object.getString("temp1"));
txt_weather_detail.setText(object.getString("weather"));
} catch (Exception e) {
e.printStackTrace();
}
}
};
要注意 rawQuery 的字串拼接有 SQL 注入風險,正式專案應改用 selection 與 selectionArgs 的參數化查詢。
將 citychina 資料庫檔放在 res/raw 目錄,首次啟動時複製到程式的資料庫目錄:
/** 將資源檔中的資料庫複製到程式資料庫目錄 */
public void copyDatabase() {
File file = new File(DB_PATH);
if (!file.isDirectory()) {
file.mkdir();
}
String dbfile = DB_PATH + "/" + DBNAME;
try {
if (new File(dbfile).length() == 0) {
FileOutputStream fos = new FileOutputStream(dbfile);
byte[] buffer = new byte[BUFFER_SIZE];
readDB(fos, buffer, R.raw.citychina);
fos.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void readDB(FileOutputStream fos, byte[] buffer, int db_id) throws IOException {
int count;
InputStream is = this.context.getResources().openRawResource(db_id);
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
is.close();
}
範例中城市名稱是寫死的,實務上建議用定位服務取得目前所在城市,再拿去查表。此外城市名稱的「正規化」是個隱形難題:使用者定位回傳的可能是「深圳市」,而資料表裡存的是「深圳」,需要額外做後綴清理;直轄市、同名縣市也需要處理。這類問題沒有通用解,只能依實際資料與需求逐一調整。
另外提醒:此類非官方公開介面隨時可能變更或停止服務,正式上線的產品應準備備援方案或改用有 SLA 保障的商業氣象服務。
Android 輕量數據持久化:SharedPreferences 實戰(以飛行模式開關為例)
需求很常見:模擬系統設置中的「飛行模式」開關,切換狀態後重啟應用仍能記住上次的選擇。這正是 SharedPreferences 的適用場景——以鍵值對形式保存少量簡單數據
Android 拼圖小遊戲:方塊切割、點擊與手勢操作
拼圖遊戲的整體思路拼圖遊戲可以拆解為三件事:切圖、移動、判定勝利。先把大圖切成若干小方塊,用 GridLayout 排列;再讓空白方塊與相鄰方塊交換;最後檢查每個方塊是否
手把手教你用 ViewPager 自定義實現 Banner 輪播
歡迎關注 Android 開源網絡框架 NoHttp:https://github.com/yanzhenjie/NoHttp實際開發中,很多 App 都會做一個廣告輪播
用 Design Support Library 實現 QQ 風格側滑與滑動菜單導航
2015 年 Google I/O 大會發布了更完善的 Material Design 規范,並推出了 Android Design Support Library。這個