編輯:關於 Android 程式設計
前陣子一直有人回報說我以前寫的那個小 App 抓不到資料了——就是那個《Android 簡易版天氣預報 app》。今天重新跑一次找原因,發現大概是接口那邊做了限制,同一個 apikey 沒辦法在多台手機上同時使用。
順便把舊程式碼翻出來看,實在寫得有點亂,介面也不好看,乾脆整份重寫了一輪,開發環境也換成 Android Studio。
最終效果如下:

專案結構:

一、取得地區清單
做天氣 App 的第一步,是先把國內的地區清單弄到手。中國天气网開放了這方面的接口,訪問 https://www.weather.com.cn/data/list3/city.xml 就能拿到各省清單與代號。

從上圖可以看到廣東省的代號是 28,那麼要抓廣東省底下的城市,接口就是 https://www.weather.com.cn/data/list3/city28.xml:

依此類推還能再往下抓到縣區層級,地區選擇的開頭部分就完成了。
二、取得天氣資料
百度的 APIStore 上有大量接口,涵蓋生活各個層面。透過其中一個天氣接口,可以拿到含天氣資訊的 JSON 字串,天氣預報功能就靠它。
使用前要先有百度帳號,登入後在「API」分頁點擊「您自己的 apikey」查看專屬金鑰。這個值是每個開發者與 App 的唯一識別,必須妥善保管,有了它才能進行下一步。

該接口免費,但也因此不太穩定,我在除錯時就常常出錯。取回的資料是 JSON 格式,需要在程式裡解析。

三、資料庫設計
地區清單這種資料基本上不會變,所以第一次聯網抓到之後就存進資料庫,之後直接讀本地即可。這裡設計了四個 Model:省份 Province、城市 City、縣 County、每小時預測 HourlyWeather。
/** 省份 */
public class Province {
private String provinceName;
private String provinceId;
public String getProvinceId() { return provinceId; }
public String getProvinceName() { return provinceName; }
public void setProvinceId(String provinceId) { this.provinceId = provinceId; }
public void setProvinceName(String provinceName) { this.provinceName = provinceName; }
}
/** 每小時天氣預測 */
public class HourlyWeather {
private String time; // 預測時間
private String temp; // 溫度
private String pop; // 降水概率
private String wind; // 風力
public HourlyWeather(String time, String temp, String pop, String wind) {
this.time = time;
this.temp = temp;
this.pop = pop;
this.wind = wind;
}
// getter 略
}
City 與 County 的結構與 Province 類似,只是各自多帶一個上層 ID 作為關聯。
接著寫 DatabaseHelper 繼承 SQLiteOpenHelper,建立三張表:
public class DatabaseHelper extends SQLiteOpenHelper {
private final String CREATE_PROVINCE = "create table Province ("
+ "provinceName text, provinceId text)";
private final String CREATE_CITY = "create table City("
+ "cityName text, cityId text, provinceId text)";
private final String CREATE_COUNTY = "create table County("
+ "countyName text, countyId text, cityId text)";
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_PROVINCE);
db.execSQL(CREATE_CITY);
db.execSQL(CREATE_COUNTY);
}
}
再包一層 WeatherDB 負責實際存取。這裡有個關鍵:城市是掛在某個省份底下的,所以查某省的城市清單時,必須把 provinceId 當作條件傳進去。
public class WeatherDB {
private final String DataBaseName = "ZyWeather";
private final int VERSION = 1;
private SQLiteDatabase database;
private static WeatherDB weatherDB;
private WeatherDB(Context context) {
DatabaseHelper helper = new DatabaseHelper(context, DataBaseName, null, VERSION);
database = helper.getWritableDatabase();
}
/** 單例 */
public static WeatherDB getInstance(Context context) {
if (weatherDB == null) weatherDB = new WeatherDB(context);
return weatherDB;
}
public void saveProvinces(List<Province> provinceList) {
if (provinceList != null && provinceList.size() > 0) {
ContentValues values = new ContentValues();
for (Province p : provinceList) {
values.put("provinceName", p.getProvinceName());
values.put("provinceId", p.getProvinceId());
database.insert("Province", null, values);
values.clear(); // 別忘了清空,否則資料會累加
}
}
}
/** 依省份撈城市 */
public List<City> getAllCity(String provinceId) {
List<City> list = new ArrayList<City>();
Cursor cursor = database.query("City", null,
"provinceId = ?", new String[]{provinceId}, null, null, null);
if (cursor.moveToFirst()) {
do {
City city = new City();
city.setCityName(cursor.getString(cursor.getColumnIndex("cityName")));
city.setCityId(cursor.getString(cursor.getColumnIndex("cityId")));
city.setProvinceId(provinceId);
list.add(city);
} while (cursor.moveToNext());
}
return list;
}
// saveCities / saveCounties / getAllProvince / getAllCountry 依此類推
}
四、聯網層
整個 App 只寫一支靜態方法來處理所有網路請求,放在 HttpUtil 裡:
public class HttpUtil {
public static void sendHttpRequest(final String address, final HttpCallbackListener listener) {
new Thread(new Runnable() {
public void run() {
HttpURLConnection connection = null;
try {
URL url = new URL(address);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(8000);
connection.setReadTimeout(8000);
connection.setRequestProperty("apikey", "填入自己的apikey");
connection.connect();
InputStream inputStream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader bufferedReader = new BufferedReader(reader);
StringBuilder response = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
response.append(line);
}
if (listener != null) listener.onFinish(response.toString());
} catch (Exception e) {
if (listener != null) listener.onError(e);
} finally {
if (connection != null) connection.disconnect();
}
}
}).start();
}
}
apikey 只有抓天氣時用得到,抓地區清單其實不需要,這裡為了省事一起放進 request header。
五、工具類
回呼介面很單純:
public interface HttpCallbackListener {
void onFinish(String response);
void onError(Exception e);
}
Utility 負責兩件事:把用分隔符串起來的地區字串拆成物件存庫,以及解析天氣 JSON。
public class Utility {
/** 解析並保存省級資料 */
public static boolean saveProvincesResponse(WeatherDB weatherDB, String response) {
if (!TextUtils.isEmpty(response)) {
String[] allProvinces = response.split(",");
if (allProvinces != null && allProvinces.length > 0) {
List<Province> provinceList = new ArrayList<>();
for (String p : allProvinces) {
String[] array = p.split("\\|");
Province province = new Province();
province.setProvinceId(array[0]);
province.setProvinceName(array[1]);
provinceList.add(province);
}
weatherDB.saveProvinces(provinceList);
return true;
}
}
return false;
}
// saveCitiesResponse / saveCountiesResponse 結構相同,多帶一個上層 ID
/** 解析天氣 JSON,並把摘要寫進 SharedPreferences */
public static void handleWeatherResponse(Context context, String response) {
try {
JSONObject jsonobject = new JSONObject(response);
JSONArray title = jsonobject.getJSONArray("HeWeather data service 3.0");
JSONObject first = (JSONObject) title.get(0);
JSONObject basic = (JSONObject) first.get("basic");
JSONObject update = (JSONObject) basic.get("update");
JSONArray daily = (JSONArray) first.get("daily_forecast");
JSONObject today = (JSONObject) daily.get(0);
JSONObject cond = (JSONObject) today.get("cond");
JSONObject temp = (JSONObject) today.get("tmp");
JSONObject astro = (JSONObject) today.get("astro");
JSONObject wind = (JSONObject) today.get("wind");
JSONArray hourly = (JSONArray) first.get("hourly_forecast");
WeatherActivity.weatherList.clear();
for (int i = 0; i < hourly.length(); i++) {
JSONObject json = hourly.getJSONObject(i);
JSONObject json_wind = (JSONObject) json.get("wind");
String[] array = json.getString("date").split(" ");
HourlyWeather weather = new HourlyWeather(
array[1],
"溫度:" + json.getString("tmp") + "℃",
"降水概率:" + json.getString("pop"),
"風力:" + json_wind.getString("dir") + " " + json_wind.getString("sc") + "級");
WeatherActivity.weatherList.add(weather);
}
saveWeatherInfo(context,
basic.getString("city"),
astro.getString("sr"), astro.getString("ss"),
cond.getString("txt_d"), cond.getString("txt_n"),
wind.getString("dir") + " " + wind.getString("sc") + "級",
today.getString("pop"),
temp.getString("min") + "℃~" + temp.getString("max") + "℃",
update.getString("loc"));
} catch (Exception e) {
e.printStackTrace();
}
}
private static void saveWeatherInfo(Context context, String cityName, String sunriseTime,
String sunsetTime, String dayWeather, String nightWeather,
String windText, String pop, String tempText, String updateTime) {
SharedPreferences.Editor editor =
context.getSharedPreferences("Weather", Context.MODE_PRIVATE).edit();
editor.putString("cityName", cityName);
editor.putString("sunriseTime", sunriseTime);
editor.putString("sunsetTime", sunsetTime);
editor.putString("dayWeather", dayWeather);
editor.putString("nightWeather", nightWeather);
editor.putString("wind", windText);
editor.putString("pop", pop);
editor.putString("temp", tempText);
editor.putString("updateTime", updateTime);
editor.commit();
}
}
六、每小時預報的適配器
動態圖裡那一列列每小時預報是用 ListView 呈現的,需要一個適配器。列表項版面如下:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<!-- 時間 -->
<TextView android:id="@+id/forecastTime"
android:layout_width="0dp" android:layout_height="match_parent"
android:layout_weight="2" android:gravity="center" android:textSize="20sp" />
<LinearLayout android:layout_width="0dp" android:layout_height="match_parent"
android:layout_weight="5" android:orientation="vertical">
<LinearLayout android:layout_width="match_parent" android:layout_height="0dp"
android:layout_weight="1" android:gravity="center"
android:orientation="horizontal">
<TextView android:id="@+id/forecastTemp"
android:layout_width="0dp" android:layout_height="match_parent"
android:layout_weight="1" android:gravity="center" />
<TextView android:id="@+id/forecastPop"
android:layout_width="0dp" android:layout_height="match_parent"
android:layout_weight="1" android:gravity="center" />
</LinearLayout>
<TextView android:id="@+id/forecastWind"
android:layout_width="match_parent" android:layout_height="0dp"
android:layout_weight="1" android:gravity="center" />
</LinearLayout>
</LinearLayout>
public class WeatherAdapter extends ArrayAdapter<HourlyWeather> {
private int resourceId;
private Context context;
public WeatherAdapter(Context context, int textViewResourceId,
List<HourlyWeather> objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.resourceId = textViewResourceId;
}
public View getView(int position, View convertView, ViewGroup parent) {
HourlyWeather weather = getItem(position);
View view = LayoutInflater.from(context).inflate(resourceId, null);
((TextView) view.findViewById(R.id.forecastTime)).setText(weather.getTime());
((TextView) view.findViewById(R.id.forecastTemp)).setText(weather.getTemp());
((TextView) view.findViewById(R.id.forecastPop)).setText(weather.getPop());
((TextView) view.findViewById(R.id.forecastWind)).setText(weather.getWind());
return view;
}
}
七、Activity 的編寫
先完成地區選擇頁 ChooseAreaActivity,版面只有一個標題 TextView 與一個 ListView:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout android:layout_width="match_parent" android:layout_height="50dp">
<TextView android:id="@+id/title"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_centerInParent="true" android:textSize="24sp" />
</RelativeLayout>
<ListView android:id="@+id/listView"
android:layout_width="match_parent" android:layout_height="match_parent" />
</LinearLayout>
它要做的事有兩件:把地區清單分三層載入,以及把使用者最後選的 County 名稱傳給 WeatherActivity。設計上用 currentLevel 標記目前在第幾層,返回鍵就能逐層往回走。
public class ChooseAreaActivity extends AppCompatActivity {
public static final int LEVEL_PROVINCE = 0;
public static final int LEVEL_CITY = 1;
public static final int LEVEL_COUNTY = 2;
private ProgressDialog progressDialog;
private TextView titleText;
private ListView listView;
private ArrayAdapter<String> adapter;
private WeatherDB weatherDB;
private List<String> dataList;
private List<Province> provinceList;
private List<City> cityList;
private List<County> countyList;
private Province selectedProvince;
private City selectedCity;
private int currentLevel;
private boolean isFromWeatherActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isFromWeatherActivity = getIntent().getBooleanExtra("ChooseArea", false);
SharedPreferences sp = getSharedPreferences("Weather", Context.MODE_PRIVATE);
// 已選過縣區、且不是從天氣頁跳來的,直接進天氣頁
if (!TextUtils.isEmpty(sp.getString("CountyName", "")) && !isFromWeatherActivity) {
startActivity(new Intent(this, WeatherActivity.class));
finish();
return;
}
setContentView(R.layout.activity_choose_area);
listView = (ListView) findViewById(R.id.listView);
titleText = (TextView) findViewById(R.id.title);
dataList = new ArrayList<>();
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, dataList);
listView.setAdapter(adapter);
weatherDB = WeatherDB.getInstance(this);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
if (currentLevel == LEVEL_PROVINCE) {
selectedProvince = provinceList.get(index);
queryCities();
} else if (currentLevel == LEVEL_CITY) {
selectedCity = cityList.get(index);
queryCounties();
} else if (currentLevel == LEVEL_COUNTY) {
String countyName = countyList.get(index).getCountyName();
Intent intent = new Intent(ChooseAreaActivity.this, WeatherActivity.class);
intent.putExtra("CountyName", countyName);
startActivity(intent);
finish();
}
}
});
queryProvinces();
}
/** 先查本地,查不到再走網路 */
private void queryProvinces() {
showProgressDialog();
provinceList = weatherDB.getAllProvince();
if (provinceList.size() > 0) {
fillAdapter(provinceList, "中國");
currentLevel = LEVEL_PROVINCE;
closeProgressDialog();
} else {
queryFromServer(null, "province");
}
}
private void queryFromServer(final String code, final String type) {
String address = TextUtils.isEmpty(code)
? "https://www.weather.com.cn/data/list3/city.xml"
: "https://www.weather.com.cn/data/list3/city" + code + ".xml";
HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
boolean result;
if ("province".equals(type)) {
result = Utility.saveProvincesResponse(weatherDB, response);
} else if ("city".equals(type)) {
result = Utility.saveCitiesResponse(weatherDB, response,
selectedProvince.getProvinceId());
} else {
result = Utility.saveCountiesResponse(weatherDB, response,
selectedCity.getCityId());
}
if (result) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if ("province".equals(type)) queryProvinces();
else if ("city".equals(type)) queryCities();
else queryCounties();
}
});
}
}
@Override
public void onError(Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(ChooseAreaActivity.this, "加載失敗", Toast.LENGTH_SHORT).show();
}
});
}
});
closeProgressDialog();
}
/** 返回鍵逐層回退 */
@Override
public void onBackPressed() {
if (currentLevel == LEVEL_COUNTY) queryCities();
else if (currentLevel == LEVEL_CITY) queryProvinces();
else {
if (isFromWeatherActivity) startActivity(new Intent(this, WeatherActivity.class));
finish();
}
}
}
WeatherActivity 的版面比較多 TextView,但我只想保持簡單,就把各項數據用文字直接排出來。它負責三件事:啟動時同步資料、處理「切換城市」與「更新資料」兩個按鈕、把 SharedPreferences 裡的摘要填進畫面並掛上每小時預報的 adapter。
private void queryFromServer(final String countyName) {
try {
String url = "https://apis.baidu.com/heweather/weather/free?city=";
String name = new String(countyName.getBytes("UTF-8"), "iso-8859-1");
HttpUtil.sendHttpRequest(url + name, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
Utility.handleWeatherResponse(WeatherActivity.this, response);
runOnUiThread(new Runnable() {
@Override
public void run() { showWeather(); }
});
}
@Override
public void onError(Exception e) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(WeatherActivity.this, "同步失敗", Toast.LENGTH_LONG).show();
weatherRefresh.setText("更新數據");
}
});
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
private void showWeather() {
cityName.setText(sharedPreferences.getString("cityName", "未知"));
sunriseTime.setText("日出:" + sharedPreferences.getString("sunriseTime", "未知"));
sunsetTime.setText("日落:" + sharedPreferences.getString("sunsetTime", "未知"));
DayNightWeather.setText("日:" + sharedPreferences.getString("dayWeather", "未知")
+ " 夜:" + sharedPreferences.getString("nightWeather", "未知"));
temp.setText("溫度:" + sharedPreferences.getString("temp", "未知"));
wind.setText("風力:" + sharedPreferences.getString("wind", "未知"));
pop.setText("降水概率:" + sharedPreferences.getString("pop", "未知"));
updateTime.setText("發布時間:" + sharedPreferences.getString("updateTime", "未知"));
listview.setAdapter(new WeatherAdapter(this, R.layout.hourly_weather, weatherList));
weatherRefresh.setText("更新數據");
}
八、一個還沒解的謎
很奇怪的是,這個小 App 在我 4.4 的小米手機上跑得很正常,換到 5.1 的模擬器和華為手機卻抓不到資料,回傳的 JSON 說城市未知。查了很久還是沒搞明白,只好先擱著。
程式碼下載位址請見原文。
以上就是本文的全部內容,希望對大家的學習有幫助。
仿墨跡天氣:在Android中透過自訂zip包換膚
這裡來聊聊墨跡天氣的換膚做法。需要先聲明:以下原理是我透過反編譯並參考網上一些資料推測出來的,僅供參考;如果你有更理想的方式,非常歡迎一起交流。墨跡天氣下載的皮膚本質上就
Android 鬧鐘功能的完整實作方案與踩坑記錄
先前有人在後台問有沒有設定鬧鐘的範例,當時答應要寫,一直騰不出時間,最近又有人催,於是決定認真做一個。鬧鐘這件事看起來簡單,實際坑不少。我把常用邏輯抽成了一個可直接呼叫的
Android Socket 即時消息推送原理與實作
概念 Socket 通訊適合用於需要即時雙向傳遞訊息的情境。這個範例以伺服器作為中繼站,手機客戶端將訊息送到伺服器,伺服器再依目標 socketID 推送给定客戶端。
用 ListView 實現三級節點菜單(可擴展至多級)
二級節點想必大家都熟悉,用 ExpandableListView 就能輕鬆搞定。但如果要實現三級甚至多級菜單呢?繼續硬套 ExpandableListView 就會變得非