編輯:關於 Android 程式設計
做電視盒子 Launcher 時,一個看似簡單的需求——「自動定位並顯示當地天氣」——背後其實藏著不少坑。本文把整個開發歷程與踩過的雷完整記錄下來,希望讓你少走幾趟彎路。

接到需求後我的思路是:先寫死一個城市(例如深圳)把天氣抓下來跑通,再回頭做定位。因為公司做的是海外生意,天氣來源選了 Yahoo 的 API。
原本網上流傳的作法是把 woeid 拼進請求,但那條路早就失效了:

於是改上 Yahoo 開發者網站重新找接口。最初參考的例子用 SAX 解析 XML,我也照著做,結果卡關——既然對 JSON 解析更熟悉,果斷換路線。Yahoo 回傳的原始 JSON 長這樣:

一坨沒排版的字串,看起來確實頭暈。這裡推薦一個幫了大忙的工具:用線上 JSON 格式化網站(json.cn)先把它排整齊。

結構清楚之後就簡單了,資料是層層嵌套的,逐層取即可。網路請求我用了 Volley,一行建立佇列,回呼寫起來相當清爽。
private RequestQueue mQueue;
// onCreate 中
mQueue = Volley.newRequestQueue(this);
private void getData(String url) {
JsonObjectRequest request = new JsonObjectRequest(url, null,
new Listener() {
public void onResponse(JSONObject response) {
try {
JSONObject query = response.getJSONObject("query");
JSONObject channel = query.getJSONObject("results")
.getJSONObject("channel");
// 地點資訊:城市、區域、國家
JSONObject location = channel.getJSONObject("location");
tx_city.setText(location.getString("city")
+ location.getString("region")
+ location.getString("country"));
JSONObject item = channel.getJSONObject("item");
JSONArray forecast = item.getJSONArray("forecast");
String description = item.getString("description");
// 從描述文字中擷取 Yahoo 天氣圖示網址
StringBuilder sb = new StringBuilder(description);
String imgUrl = description.substring(
description.indexOf("<img src=\"") + "<img src=\"".length(),
description.lastIndexOf("\"/>"));
// 只取當天(索引 0)
JSONObject today = forecast.getJSONObject(0);
((TextView) findViewById(R.id.tx_condition))
.setText(today.getString("text"));
// 華氏轉攝氏:(F - 32) / 1.8
int low = (int) ((Integer.parseInt(today.getString("low")) - 32) / 1.8);
int high = (int) ((Integer.parseInt(today.getString("high")) - 32) / 1.8);
tx_temp.setText(low + "/" + high + getResources().getString(R.string.str_temp));
if (imgUrl.length() == 37) {
img_weather.setImageResource(parseIcon2(imgUrl.substring(31, 37)));
} else if (imgUrl.length() == 36) {
img_weather.setImageResource(parseIcon2(imgUrl.substring(31, 36)));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new ErrorListener() {
public void onErrorResponse(VolleyError arg0) { }
});
mQueue.add(request);
}
Yahoo 自帶的圖示醜得有點驚人,所以另外做了一張對照表,把它的代碼映射到自家素材:
private int parseIcon2(String strIcon) {
if (strIcon == null) return -1;
if ("31.gif".equals(strIcon) || "32.gif".equals(strIcon)
|| "33.gif".equals(strIcon) || "34.gif".equals(strIcon)
|| "36.gif".equals(strIcon)) return R.drawable.sunny03;
if ("23.gif".equals(strIcon) || "26.gif".equals(strIcon)
|| "27.gif".equals(strIcon) || "28.gif".equals(strIcon)
|| "30.gif".equals(strIcon) || "44.gif".equals(strIcon)) return R.drawable.cloudy03;
if ("29.gif".equals(strIcon)) return R.drawable.shade03;
if ("40.gif".equals(strIcon)) return R.drawable.shower01;
if ("4.gif".equals(strIcon)) return R.drawable.thunder_shower03;
if ("13.gif".equals(strIcon)) return R.drawable.snow_shower03;
if ("11.gif".equals(strIcon) || "12.gif".equals(strIcon)) return R.drawable.l_rain03;
if ("45.gif".equals(strIcon) || "47.gif".equals(strIcon)
|| "39.gif".equals(strIcon)) return R.drawable.h_rain03;
// 其餘天氣代碼依此類推
return R.drawable.sunny03;
}
寫到這裡,深圳的天氣已經能在盒子上正確顯示。當時是在 Launcher 裡註冊動態廣播監聽網路狀態,有網路時就把天氣區塊顯示出來。
接著才是定位。事前如果先把方案列出來評估,應該能省下大量時間——這點值得記取。
高德:直接淘汰,公司做的是海外生意。
GPS:盒子上沒有 GPS 模組,淘汰。
WiFi 定位:網上常見的做法是呼叫 Google 的定位服務。把現成程式碼貼進來之後,卻永遠拿到 null:


mm 編譯通過後,out 目錄下生成了對應的 lib 與 apk。手動把 .so 放進 system/lib、調整權限,再把 apk push 進盒子替換——結果一連上網路就無限閃屏。logcat 的報錯如下:

換成百度最新的 jar 與 .so 重來一次,錯誤一模一樣。上網查說可能是處理器不相容,問了硬體同事才知道我們是 64 位處理器但系統跑 32 位。於是回頭把所有 abi 目錄的 .so 都試了一遍:

全部閃屏,一輪編譯測試下來耗掉不少時間,問題依舊懸而未決(究竟是相容性問題還是 .so 設定有誤,至今仍無頭緒,若有人讀到願意指點,感激不盡)。
和同事討論後決定換個思路:定位交給獨立的 APK 去做,再把結果傳回 Launcher。兩 App 之間最初嘗試用 SharedPreference 共享:


打印出來確實拿到了 "lucy" 之類的測試值,但真正要傳的 city = res.addressComponents.city 卻傳不過去。於是改用廣播傳值:
Intent i = new Intent();
i.setAction("com.example.perference.shared_id");
i.putExtra("city", city);
sendBroadcast(i);
Launcher 端:網路就緒時發出廣播
if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)
|| action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)
|| action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Intent send = new Intent();
send.setAction("com.weather.broadcast");
send.putExtra("launcher", "weather");
Launcher.this.sendBroadcast(send);
}
定位 APK 端:接收廣播並啟動服務
public class MyBroadcast extends BroadcastReceiver {
private final String weather_broadcat = "com.weather.broadcast";
public void onReceive(Context content, Intent intent) {
if (intent.getAction().equals(weather_broadcat)) {
String str = intent.getExtras().getString("launcher");
content.startService(new Intent(content, MyService.class));
}
}
}
定位服務:開啟定位、反地理編碼、回傳城市
public class MyService extends Service {
private static String city;
private BMapManager mBMapMan;
private LocationListener mLocationListener;
private MKSearch mSearch;
private Handler handler = new Handler();
public void onCreate() {
initBaiDuMap();
mBMapMan.getLocationManager().requestLocationUpdates(mLocationListener);
mBMapMan.getLocationManager().enableProvider(MKLocationManager.MK_GPS_PROVIDER);
mBMapMan.start();
}
public void initBaiDuMap() {
mBMapMan = new BMapManager(getApplication());
mBMapMan.init("你的百度 AK", null);
mBMapMan.start();
mLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint pt = new GeoPoint((int) (location.getLatitude() * 1e6),
(int) (location.getLongitude() * 1e6));
initMapSerach();
mSearch.reverseGeocode(pt);
}
}
};
}
private void initMapSerach() {
mSearch = new MKSearch();
mSearch.init(mBMapMan, new MKSearchListener() {
public void onGetAddrResult(MKAddrInfo res, int error) {
if (error != 0 || res == null) return;
city = res.addressComponents.city;
String pro = res.addressComponents.province;
new Thread() {
public void run() {
Intent i = new Intent();
i.setAction("com.example.perference.shared_id");
i.putExtra("city", city);
sendBroadcast(i);
// 每 10 分鐘更新一次
handler.postDelayed(this, 600000);
}
}.start();
}
// 其餘 onGetXxxResult 留空即可
});
}
}
Launcher 端:接收城市後拼接 Yahoo 查詢語句
private BroadcastReceiver netReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action == null) return;
if (action.equals(weather_receive_action)) {
String weatherCity = intent.getExtras().getString("city");
urlcity = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20"
+ "weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20"
+ "geo.places(1)%20where%20text%3D'" + weatherCity + "')"
+ "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
getData(urlcity);
}
// 其餘分支:更新應用列表、Wifi 訊號、時間顯示等
}
};
定位只在移動網路下有效,若客戶使用有線網路,就得讓使用者自己輸入城市。為此保留了一個查詢按鈕:
query_button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// XML 中把 EditText 設為 gone,避免開機自動聚焦彈出軟鍵盤
etCity.setVisibility(View.VISIBLE);
final String mCityStr = etCity.getText().toString();
if (!mCityStr.isEmpty()) {
tx_city.setVisibility(View.GONE);
String CityCodeUrl = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20"
+ "from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20"
+ "from%20geo.places(1)%20where%20text%3D'" + mCityStr + "')"
+ "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys";
getData(CityCodeUrl);
} else {
Toast.makeText(Launcher.this, "Please enter a city name",
Toast.LENGTH_SHORT).show();
}
}
});
回頭看,這個需求真正的成本不在寫功能,而在選型:先確認目標市場、硬體能力與服務可用性,再動手。天氣接口會掛、第三方定位 SDK 會與系統 .so 不相容、SharedPreference 跨 App 不一定可靠——這些都不是程式邏輯問題,卻最耗時間。若文中內容有誤,也歡迎指正。
Android 增量更新完全解析:是增量,不是熱修復
一、概述 最近一直在關注熱修復的東西,偶爾聊天時談到了增量更新——當然,兩者完全不是一回事。藉此我找了些資料,收集整理了一下。本來不想寫部落格的,因為核心基本都是工具的實
自定義屬性實作帶邊框線的 TextView 控制項
當系統自帶屬性無法滿足需求時,就得替控制項加上自定義屬性。這裡示範一個很典型的例子:讓文字方塊能單獨顯示左、上、右、下任一邊的邊框線。不用自定義屬性當然也做得到,但把「要
用 Gallery 與 ImageSwitcher 打造可左右無限循環的圖片瀏覽器
Gallery 天生就是拿來做橫向圖片列表的,但它有個惱人的限制:滑到頭就停了,沒辦法無限循環。要突破這個限制,關鍵在於自訂 Adapter——只要讓 getCount
Android Adapter 體系入門:視圖與資料綁定的關鍵橋樑
在 Android 開發中,只要涉及「一批資料要呈現成一列列畫面」,幾乎都繞不開 Adapter 系列類別。可以這樣理解:視圖(View)是骨架,資料是血肉,而 Adap