編輯:關於 Android 程式設計
要在 App 裡嵌入地圖、做定位與周邊搜尋,高德(AMap)SDK 是國內開發者的常見選擇。本文把接入高德地圖的核心步驟系統性地整理了一遍,從權限配置一路講到進階的傳感器羅盤效果。
接入高德前,先在清單檔案裡聲明所需權限並填入你的 API Key:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<meta-data
android:name="com.amap.api.v2.apikey"
android:value="你的APIKEY" />
核心由兩部分組成:MapView 是承載地圖的容器,AMap 則負責地圖控制,包括顯示交通、定位圖層的開關與配置。使用時先初始化容器 MapView,再取得配置物件:
private void init() {
if (aMap == null) {
aMap = mapView.getMap();
}
}
aMap.setTrafficEnabled(true);
先設定當前位置的樣式:
private void setUpMap() {
MyLocationStyle locationStyle = new MyLocationStyle();
locationStyle.strokeColor(Color.BLACK);
locationStyle.strokeWidth(1.0f);
locationStyle.radiusFillColor(0x8333);
locationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.location_marker));
aMap.setMyLocationStyle(locationStyle); // 設置定位點樣式
aMap.setLocationSource(this); // 設置監聽
aMap.setMyLocationEnabled(true); // 啟動定位圖層
}
接著繼承 LocationSource,處理定位監聽的開始與結束:
@Override
public void activate(OnLocationChangedListener arg0) {
mLocationChangedListener = arg0;
if (mLocationManager == null) {
mLocationManager = LocationManagerProxy.getInstance(this);
// 每 2 秒更新一次,最後一個參數 AMapNetwork 是定位模式
mLocationManager.requestLocationUpdates(LocationProviderProxy.AMapNetwork, 2000, 10, this);
}
}
@Override
public void deactivate() {
mLocationChangedListener = null;
if (mLocationManager != null) {
mLocationManager.removeUpdates(this);
mLocationManager.destroy();
mLocationManager = null;
}
}
再繼承 AMapLocationListener,重點實作 onLocationChanged 來更新位置:
@Override
public void onLocationChanged(AMapLocation arg0) {
if (mLocationChangedListener != null && arg0 != null) {
mLocationChangedListener.onLocationChanged(arg0);
}
}
系統默認的定位只是一個靜態圖標,並不含方向資訊。想要做出「跟著手機朝向旋轉」的效果,思路是:添加一個 Marker,再用方向傳感器即時修改它的旋轉角度。
先初始化傳感器:
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
初始化 Marker:
private void setUpMap() {
mGPSMarker = aMap.addMarker(new MarkerOptions()
.icon(BitmapDescriptorFactory.fromResource(R.drawable.location_marker))
.anchor(0.5f, 0.5f));
aMap.setLocationSource(this);
aMap.setMyLocationEnabled(true);
}
在啟動位置監聽時註冊傳感器,關閉時註銷:
@Override
public void activate(OnLocationChangedListener arg0) {
// ...
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
@Override
public void deactivate() {
// ...
mSensorManager.unregisterListener(this, mSensor);
}
位置移動時更新 Marker 座標:
@Override
public void onLocationChanged(AMapLocation arg0) {
if (mLocationChangedListener != null && arg0 != null) {
mLocationChangedListener.onLocationChanged(arg0);
mGPSMarker.setPosition(new LatLng(arg0.getLatitude(), arg0.getLongitude()));
}
}
方向變化時更新 Marker 角度,這裡還需要換算螢幕旋轉角度:
@Override
public void onSensorChanged(SensorEvent event) {
if (System.currentTimeMillis() - lastTime < TIME_SENSOR) {
return;
}
switch (event.sensor.getType()) {
case Sensor.TYPE_ORIENTATION: {
float x = event.values[0];
x += getScreenRotationOnPhone(this);
x %= 360.0F;
if (x > 180.0F) x -= 360.0F;
else if (x < -180.0F) x += 360.0F;
if (Math.abs(mAngle - 90 + x) < 3.0f) {
break;
}
mAngle = x;
if (mGPSMarker != null) {
mGPSMarker.setRotateAngle(-mAngle);
aMap.invalidate();
}
lastTime = System.currentTimeMillis();
}
}
}
/**
* 獲取當前螢幕旋轉角度
* @return 0 表示直式; 90 表示左橫式; 180 表示反向直式; 270 表示右橫式
*/
public static int getScreenRotationOnPhone(Context context) {
final Display display = ((WindowManager) context
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
switch (display.getRotation()) {
case Surface.ROTATION_0: return 0;
case Surface.ROTATION_90: return 90;
case Surface.ROTATION_180: return 180;
case Surface.ROTATION_270: return -90;
}
return 0;
}
LatLngBounds bounds = new LatLngBounds.Builder()
.include(new LatLng(22.117719, 112.323274))
.include(new LatLng(22.117719, 114.323274))
.include(new LatLng(24.117719, 112.323274))
.include(new LatLng(24.117719, 114.323274))
.build();
aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10));
aMap.moveCamera(CameraUpdateFactory.zoomBy(8));
aMap.setOnMapLoadedListener(this); // 設置地圖顯示監聽器
ArrayList<BitmapDescriptor> icons = new ArrayList<BitmapDescriptor>();
icons.add(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE));
// ...
aMap.addMarker(new MarkerOptions()
.icons(icons) // 顯示多圖片
.period(2) // 變化週期
.position(new LatLng(23.118674, 113.321614))
.anchor(0.5f, 0.5f) // 錨點位置
.title("fuliyinkai") // 點擊顯示文字
).showInfoWindow(); // 默認顯示
aMap.setInfoWindowAdapter(this); // 點擊標記顯示自定義浮動 View
aMap.addCircle(new CircleOptions()
.center(new LatLng(23.118674, 113.321614))
.fillColor(0x88888888)
.strokeColor(Color.BLACK)
.strokeWidth(5)
.radius(400));
文字提示查詢:
Inputtips inputtips = new Inputtips(this, new InputtipsListener() {
@Override
public void onGetInputtips(List<Tip> tips, int arg1) {
tips.get(0).getName(); // 獲取匹配的單個資料名稱
}
});
try {
inputtips.requestInputtips(content, city);
} catch (AMapException e) {
e.printStackTrace();
}
POI 檢索:
// 第一個參數是關鍵字,第二個是 POI 類型,第三個是檢索區域(空字串代表全國)
query = new PoiSearch.Query(keyWord, "", editCity.getText().toString());
query.setPageSize(10); // 每頁最多返回多少條 poiitem
query.setPageNum(currentPage); // 檢索第幾頁
poiSearch = new PoiSearch(this, query);
poiSearch.setOnPoiSearchListener(this); // 主要執行 onPoiSearched()
poiSearch.searchPOIAsyn();
@Override
public void onPoiSearched(PoiResult result, int rCode) {
dismissProgressDialog(); // 隱藏對話框
if (rCode == 0) {
if (result != null && result.getQuery() != null) {
if (result.getQuery().equals(query)) {
poiResult = result;
List<PoiItem> poiItems = poiResult.getPois();
List<SuggestionCity> suggestionCities = poiResult.getSearchSuggestionCitys();
if (poiItems != null && poiItems.size() > 0) {
aMap.clear();
PoiOverlay poiOverlay = new PoiOverlay(aMap, poiItems);
poiOverlay.removeFromMap();
poiOverlay.addToMap();
poiOverlay.zoomToSpan();
} else if (suggestionCities != null && suggestionCities.size() > 0) {
showSuggestCity(suggestionCities);
} else {
ToastUtil.show(PoiKeywordSearchActivity.this, R.string.no_result);
}
}
} else {
ToastUtil.show(PoiKeywordSearchActivity.this, R.string.no_result);
}
} else if (rCode == 27) {
ToastUtil.show(PoiKeywordSearchActivity.this, R.string.error_network);
} else if (rCode == 32) {
ToastUtil.show(PoiKeywordSearchActivity.this, R.string.error_key);
} else {
ToastUtil.show(PoiKeywordSearchActivity.this, getString(R.string.error_other) + rCode);
}
}
Android Touch 事件傳遞機制全解析:從 WMS 到 View 樹的源碼追蹤
事件分發是 Android 裡看似基礎、想真正串通卻頗費功夫的一塊。本文以 Android 4.4 源碼為例,把 Touch 事件從系統服務端一路追到 View 樹,中間
仿 QQ「掃一掃」:為 zxing 二維碼工程加上相冊識別、手電筒與二維碼生成
二維碼幾乎已經是每個 App 的標配。之前專案裡第一次接入時,我只做了最基礎的掃碼功能;後來仔細研究了 QQ 的「掃一掃」,發現它其實把幾個高頻需求都涵蓋了:從相冊選圖識
手把手帶你入門 Android 逆向分析
很多技術文章喜歡一上來鋪陳一大堆行業現狀、研究背景,寫得像畢業論文。這裡不來這套,先上兩張圖直觀感受一下成果。 第一張是把代碼注入到地圖 App 裡,啟動時彈出一個浮窗
為 UITableView 打造長按拖動排序功能
效果預覽 項目地址:DraggableTableView 所有 Cell 均可自由拖拽。 固定首個 Cell 不被拖動。 限制長按的觸發區域。 實現原理 為 UI