編輯:關於 Android 程式設計
到百度開放平台完成應用註冊即可拿到 appkey,定位時用它做身分驗證。註冊時選擇 Android 端並勾選所有權限。

下載定位 SDK 後解壓到專案的 libs 目錄,接著在 application 標籤下補齊權限、Service 與 API_KEY。這段設定檔看起來冗長,但每一行都有實際用途,馬虎不得。
<!-- 網路定位 -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- GPS 定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- 讀取 WiFi 狀態,WiFi 資訊會用於網路定位 -->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<!-- 讀取網路狀態與運營商資訊 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<!-- 讀取手機狀態 -->
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- 寫入外部儲存,用於快取離線定位資料 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 網路定位需要連網 -->
<uses-permission android:name="android.permission.INTERNET" />
<application>
<meta-data
android:name="com.baidu.lbsapi.API_KEY"
android:value="你的 appkey" />
<service
android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote" />
</application>
在主線程宣告 LocationClient 並註冊監聽:
public LocationClient mLocationClient = null;
public BDLocationListener myListener = new MyLocationListener();
public void onCreate() {
mLocationClient = new LocationClient(getApplicationContext());
mLocationClient.registerLocationListener(myListener);
}
定位參數決定了精度、耗電與回傳內容,建議依情境調整而非照抄預設:
private void initLocation() {
LocationClientOption option = new LocationClientOption();
// 定位模式:高精度 / 低功耗 / 僅裝置
option.setLocationMode(LocationMode.Hight_Accuracy);
// 回傳座標系,預設 gcj02
option.setCoorType("bd09ll");
// 定位間隔,需大於等於 1000ms 才有效
option.setScanSpan(1000);
option.setIsNeedAddress(true); // 需要地址資訊
option.setOpenGps(true); // 允許使用 GPS
option.setLocationNotify(true); // GPS 有效時每秒輸出一次
option.setIsNeedLocationDescribe(true); // 位置語義化描述,如「在北京天安門附近」
option.setIsNeedLocationPoiList(true); // 需要 POI 清單
option.setIgnoreKillProcess(false); // stop 時是否終止定位行程
option.SetIgnoreCacheException(false); // 是否收集 CRASH 資訊
option.setEnableSimulateGps(false); // 是否過濾 GPS 模擬結果
mLocationClient.setLocOption(option);
}
BDLocation 不只是經緯度,它還區分了定位來源(GPS、網路、離線)與各種失敗原因,把這些分支處理好,除錯效率會差很多。
public class MyLocationListener implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
StringBuffer sb = new StringBuffer(256);
sb.append("time : ").append(location.getTime());
sb.append("\nerror code : ").append(location.getLocType());
sb.append("\nlatitude : ").append(location.getLatitude());
sb.append("\nlongitude : ").append(location.getLongitude());
sb.append("\nradius : ").append(location.getRadius());
if (location.getLocType() == BDLocation.TypeGpsLocation) {
sb.append("\nspeed : ").append(location.getSpeed()); // 公里/小時
sb.append("\nsatellite : ").append(location.getSatelliteNumber());
sb.append("\nheight : ").append(location.getAltitude()); // 公尺
sb.append("\ndirection : ").append(location.getDirection()); // 度
sb.append("\naddr : ").append(location.getAddrStr());
sb.append("\ndescribe : GPS 定位成功");
} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
sb.append("\naddr : ").append(location.getAddrStr());
sb.append("\noperators : ").append(location.getOperators());
sb.append("\ndescribe : 網路定位成功");
} else if (location.getLocType() == BDLocation.TypeOffLineLocation) {
sb.append("\ndescribe : 離線定位成功,離線結果同樣有效");
} else if (location.getLocType() == BDLocation.TypeServerError) {
sb.append("\ndescribe : 服務端定位失敗,可提供 IMEI 與大致時間回報");
} else if (location.getLocType() == BDLocation.TypeNetWorkException) {
sb.append("\ndescribe : 網路不通導致定位失敗,請檢查連線");
} else if (location.getLocType() == BDLocation.TypeCriteriaException) {
sb.append("\ndescribe : 缺少有效定位依據,飛行模式下常見,可嘗試重啟");
}
sb.append("\nlocationdescribe : ").append(location.getLocationDescribe());
List<Poi> list = location.getPoiList();
if (list != null) {
sb.append("\npoi size = ").append(list.size());
for (Poi p : list) {
sb.append("\npoi = ").append(p.getId() + " " + p.getName() + " " + p.getRank());
}
}
Log.i("BaiduLocationApiDemo", sb.toString());
}
}
介面網址格式如下:
https://api.map.baidu.com/telematics/v3/weather?location=北京&output=json&ak=你的key
參數說明:location 可傳城市名稱或經緯度,output 指定回傳格式,ak 是平台配發的金鑰。這裡有個容易踩的雷:定位用的移動端 appkey 在這個介面不能用,必須另外申請一個「瀏覽器端」應用,用瀏覽器端的 key 才能存取。取回資料後解析成實體物件集合再回傳。
流程是這樣的:進入 App 先彈出進度框,同時啟動定位;定位回呼中取得經緯度,透過 Handler 轉交給非 UI 線程去抓天氣;資料回來後填入 ListView,最後關掉進度框。

private void initDialog() {
mDialog = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT);
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setTitle("請稍後");
mDialog.setMessage("正在獲取天氣資料");
mDialog.show();
}
順帶處理一個實務細節:區域名稱可能為空,這時退回顯示城市名。另外別忘了先檢查網路,離線時直接提示並關閉定位,避免使用者盯著轉不完的圈圈。
@Override
public void onReceiveLocation(BDLocation location) {
String district = location.getDistrict();
if (null == district || "null".equals(district)) {
tvToday.setText(location.getCity() + " ");
} else {
tvToday.setText(district + " ");
}
String param = location.getLongitude() + "," + location.getLatitude();
Message msg = Message.obtain();
msg.obj = param;
if (isNetworkConnected()) {
mHandler.sendMessage(msg);
} else {
Toast.makeText(MainActivity.this, "請檢查網路連線", 1).show();
mLocationClient.stop();
mDialog.dismiss();
}
}
public void handleMessage(android.os.Message msg) {
mLocationClient.stop();
String param = (String) msg.obj;
mUtil.getWeatherData(param, new VolleyCallBack() {
@Override
public void onSuccess(List<DayWeather> res) {
mWeather.clear();
tvToday.append(res.get(0).getDate());
mWeather.addAll(res);
listView.setAdapter(mAdapter);
chooseBackground(res.get(0).getWeather());
mDialog.dismiss();
}
});
}
這裡用 Gson 把每一筆天氣資料直接對應成 DayWeather 物件,省下大量手動 getString。pm25 只在第一筆帶出,因此單獨塞進集合首項。
public List<DayWeather> getWeatherList(String res) throws JSONException {
List<DayWeather> list = new ArrayList<>();
JSONObject object = new JSONObject(res);
JSONArray results = object.getJSONArray("results");
JSONObject result = results.getJSONObject(0);
String pm25 = result.getString("pm25");
JSONArray weathers = result.getJSONArray("weather_data");
Gson gson = new Gson();
for (int i = 0; i < weathers.length(); i++) {
list.add(gson.fromJson(weathers.get(i).toString(), DayWeather.class));
}
list.get(0).setPm25(pm25);
return list;
}
網路請求則用 Volley,並透過回呼介面把結果往外傳:
public void getWeatherData(String name, final VolleyCallBack mCallBack) {
StringRequest mRequest = new StringRequest(getWeatherUrl(name),
new Listener<String>() {
@Override
public void onResponse(String result) {
try {
mCallBack.onSuccess(getWeatherList(result));
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError arg0) {
Toast.makeText(context, "獲取天氣資料異常", 1).show();
}
});
mQueue.add(mRequest);
}
public static String getWeatherUrl(String param) {
return "https://api.map.baidu.com/telematics/v3/weather?location="
+ param + "&output=json&ak=" + APPKEY;
}
ListView 中搭配兩種版面(當日與未來幾日),橫向那條則沿用社群常見的 HorizentalListView 實作。最終畫面如下:

實作時特別提醒兩點:一是定位權限在 Android 6.0 之後需要執行期動態申請,本文寫法需自行補上;二是 API Key 請勿硬編碼進版本庫,應放到 gradle.properties 或本地設定檔中。
一篇理清 Android 的轉場動畫(Transitions)
背景 隨著 Material Design 概念的普及,動畫與 UI 的優化在開發中變得越來越重要,而「Material Motion(-material 動態效果)」正
修正 Android 對話方塊中 EditText 取值的空指標異常
撰寫一個包含輸入欄位的對話方塊時,點擊按鈕去讀取 EditText 的內容,卻一直收到空指標異常,折騰了好一陣子才找到原因。 原本的程式碼是這樣寫的: // 更新對話方塊
打造炫目圓形菜單,輕鬆高仿建行圓形菜單
一、概述 今天打開建行 App 看存款,一看悲從中來;再一看:欸,這個圓形菜單挺炫的。於是為了排遣悲痛,我決定親手實現一次這個效果。當然還有另一個原因——當初剛學 And
使用 AChartEngine 繪製柱狀圖與餅圖
AChartEngine 是專為 Android 設計的繪圖工具庫,用它可以快速畫出柱狀圖、餅圖、折線圖等常見圖表。以下說明整合步驟與兩種圖表的資料準備方式。 一、加入依