編輯:關於 Android 程式設計
上一篇談的是基礎環境建置,這次進一步把「我的位置」圖層與彈出氣泡圖層一起做出來。
除 PopupOverlay 外,其餘圖層均已支援多實例;PanoramaOverlay 是全景圖專用的特殊圖層。
MapView 內部以一個 List 管理覆蓋物,透過 MapView.getOverlays() 的 add / remove 即可增刪;更新後必須呼叫 MapView.refresh() 才會生效,這一步很容易漏掉。
使用百度定位 SDK 必須先註冊 GPS 與網路權限。SDK 會綜合 GPS、基站與 Wi-Fi 訊號進行定位,並依實際條件(是否開啟 GPS、是否連網、是否有訊號)自動選擇定位依據。
使用者可指定優先順序:設為 GPS 優先時,SDK 會先用 GPS;若 GPS 未開啟或無可用位置資訊而網路正常,則退回網路定位(Wi-Fi 與基站)的最佳結果。想讓網路定位更精準,請記得打開手機的 Wi-Fi 開關——即使沒連任何 AP,也能作為定位參考。
將 liblocSDK4.so 複製到 libs/armeabi,把 locSDK4.0.jar 複製到專案的 libs 目錄,並在 Eclipse 中把 jar 加入 Build Path。目錄結構大致如下:
庫檔可從百度官方頁面下載:developer.baidu.com/map
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.baidu.mapapi.map.MapView
android:id="@+id/bmapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:clickable="true" >
<Button
android:id="@+id/request"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="10dp"
android:layout_marginTop="10dip"
android:background="@drawable/mylocation" />
</com.baidu.mapapi.map.MapView>
</RelativeLayout>
彈出氣泡的版面是另一個簡單的 TextView:
<TextView xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/location_tips"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/location_tips"
android:maxWidth="200.0dip"
android:minWidth="40.0dip"
android:textColor="@android:color/white" />
初始化 BMapManager。注意這一步必須在 setContentView() 之前完成,第一個參數是 API key,第二個是通用事件監聽器,用來處理授權錯誤與網路異常:
mBMapManager = new BMapManager(this);
mBMapManager.init(API_KEY, new MKGeneralListener() {
@Override
public void onGetPermissionState(int iError) {
if (iError == MKEvent.ERROR_PERMISSION_DENIED) {
showToast("API KEY 錯誤, 請檢查!");
}
}
@Override
public void onGetNetworkState(int iError) {
if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
Toast.makeText(getApplication(), "您的網路出錯啦!", Toast.LENGTH_LONG).show();
}
}
});
啟動定位。LocationClient 必須在主執行緒中宣告,並透過 registerLocationListener 註冊結果回呼:
mLocData = new LocationData();
mLocClient = new LocationClient(getApplicationContext());
mLocClient.registerLocationListener(new BDLocationListenerImpl());
LocationClientOption option = new LocationClientOption();
option.setOpenGps(true); // 開啟 GPS
option.setAddrType(LocationClientOption.ADDR_TYPE_ALL); // 回傳包含地址資訊
option.setCoorType("bd09ll"); // 百度經緯度座標
option.setScanSpan(5000); // 定位間隔 5000ms
option.disableCache(false); // 允許使用快取
option.setPoiNumber(5);
option.setPoiDistance(1000);
option.setPoiExtraInfo(true);
mLocClient.setLocOption(option);
mLocClient.start();
掛上定位圖層。繼承 MyLocationOverlay 並覆寫 dispatchTap(),就能攔截「點擊我的位置」這個手勢:
myLocationOverlay = new LocationOverlay(mMapView);
myLocationOverlay.setMarker(getResources().getDrawable(R.drawable.set));
mMapView.getOverlays().add(myLocationOverlay);
myLocationOverlay.enableCompass();
mMapView.refresh(); // 別忘了這一句
private class LocationOverlay extends MyLocationOverlay {
public LocationOverlay(MapView arg0) { super(arg0); }
@Override
protected boolean dispatchTap() {
showPopupOverlay(location); // 點自己的位置時彈出氣泡
return super.dispatchTap();
}
}
接收定位結果。這個方法會週期性觸發,間隔由 setScanSpan() 決定:
public class BDLocationListenerImpl implements BDLocationListener {
@Override
public void onReceiveLocation(BDLocation location) {
if (location == null) { return; }
MainActivity.this.location = location;
mLocData.latitude = location.getLatitude();
mLocData.longitude = location.getLongitude();
mLocData.accuracy = location.getRadius(); // 設為 0 可隱藏精度圈
mLocData.direction = location.getDerect();
myLocationOverlay.setData(mLocData);
mMapView.refresh();
if (isFirstLoc || isRequest) {
mMapController.animateTo(new GeoPoint(
(int) (location.getLatitude() * 1e6),
(int) (location.getLongitude() * 1e6)));
showPopupOverlay(location);
isRequest = false;
}
isFirstLoc = false;
}
@Override
public void onReceivePoi(BDLocation poiLocation) { }
}
顯示氣泡。PopupOverlay.showPopup() 只接受 Bitmap,所以必須先把 View 轉成 Bitmap:
private void showPopupOverlay(BDLocation location) {
TextView popText = (TextView) viewCache.findViewById(R.id.location_tips);
popText.setText("[我的位置]" + location.getAddrStr());
mPopupOverlay.showPopup(getBitmapFromView(popText),
new GeoPoint((int)(location.getLatitude() * 1e6),
(int)(location.getLongitude() * 1e6)), 15);
}
public static Bitmap getBitmapFromView(View view) {
view.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
view.buildDrawingCache();
return view.getDrawingCache();
}
關於 setScanSpan() 有一點務必理解:設為 5000ms 時,onReceiveLocation 大約每 5 秒觸發一次。當設定值大於 1000ms,SDK 走定時定位模式——若判定位置未變化就不發網路請求,直接回傳上次結果;位置改變才重新請求。若只需要定位一次,把值設為小於 1000 或不設定即可。
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <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" /> <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> <uses-permission android:name="android.permission.READ_LOGS" />
還有一項關鍵設定——註冊定位服務與 API key:
<service
android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote" />
<meta-data
android:name="com.baidu.lbsapi.API_KEY"
android:value="你的API_KEY" />
之所以要用 meta-data,是因為單獨使用定位 SDK 時需要一個 key,而它不像 MapManager 那樣可以直接在建構時賦值,只能在 manifest 中註冊。
MapView 的生命週期需與 Activity 同步,否則會出現渲染異常或資源洩漏:
@Override protected void onResume() {
mMapView.onResume();
mBMapManager.start();
super.onResume();
}
@Override protected void onPause() {
mMapView.onPause();
super.onPause();
}
@Override protected void onDestroy() {
mMapView.destroy();
if (mBMapManager != null) { mBMapManager.destroy(); mBMapManager = null; }
if (mLocClient != null) { mLocClient.stop(); }
super.onDestroy();
}

過程中遇到一個問題:把先前「手動加上 marker」的程式碼與定位圖層同時啟用時,當前位置反而無法標記。這段程式碼暫時註解掉了,原因後續再補充。
部分內容整理自百度官方文件與社群分享(blog.csdn.net/xiaanming/article/details/11380619)。定位的部分先到這裡,遇到的問題會陸續補上。
Android 仿餓了麼加入購物車的伸縮旋轉按鈕
這個效果以純自定義 View 實作,不依賴多層 ViewGroup 組合。它可以在數量為 0 時顯示提示文字,點擊後展開加號與減號,並在增減數量時播放旋轉、位移與透明
Android SQLite 資料庫使用範例
SQLite 在 Android Android 內建 SQLite,適合儲存結構化資料。開發者可透過 SQLiteOpenHelper 建立資料庫、管理版本與執行 SQ
Android ActionBar 基本用法完整整理
本文整理自 Using the Android action bar (ActionBar) - Tutorial。一、ActionBar 簡介ActionBar 位於
Android 仿微信說說:拍照、相簿與多圖上傳
功能目標這個範例實作了類似微信說说的發文流程:使用者可以透過相機拍照或從相簿選擇多張圖片,填寫文字後一起上傳。這類功能在社群、動態與分享類應用中非常常見。使用 photo