編輯:關於 Android 程式設計
App 中常有「把目前位置回報給伺服器」這類需求。實作上大致有三條路:直接用 Android 原生的 LocationManager、用百度地圖 SDK、或用天地圖 API。本文先完整示範第一種,並說明另外兩種的取用方式。
核心元件是 LocationManager。取得經緯度有兩種策略:
LocationListener 回呼。即時性最好,但需要等待首次定位。實務上通常兩者並用:先試著拿 last known,若為 null 再掛 listener 等待。
MainActivity.java
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private double latitude = 0.0;
private double longitude = 0.0;
private TextView info;
private LocationManager locationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
info = (TextView) findViewById(R.id.tv);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
getLocation(); // GPS 已開啟,直接取
} else {
toggleGPS(); // 嘗試開啟 GPS
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
getLocation(); // 稍等 2 秒後再取,給定位一點時間
}
}, 2000);
}
}
/** 透過系統設定 widget 嘗試開啟 GPS */
private void toggleGPS() {
Intent gpsIntent = new Intent();
gpsIntent.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
gpsIntent.addCategory("android.intent.category.ALTERNATIVE");
gpsIntent.setData(Uri.parse("custom:3"));
try {
PendingIntent.getBroadcast(this, 0, gpsIntent, 0).send();
} catch (CanceledException e) {
e.printStackTrace();
}
}
private void getLocation() {
Location location =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
} else {
// 沒有快取位置,改為註冊監聽等待更新
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
}
info.setText("緯度:" + latitude + "\n" + "經度:" + longitude);
}
private final LocationListener locationListener = new LocationListener() {
// Provider 在「可用/暫時不可用/無服務」之間切換時觸發
@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
// Provider 被啟用時觸發,例如 GPS 被打開
@Override
public void onProviderEnabled(String provider) {
Log.e(TAG, provider);
}
// Provider 被停用時觸發,例如 GPS 被關閉
@Override
public void onProviderDisabled(String provider) {
Log.e(TAG, provider);
}
// 座標改變時觸發;若傳進的是相同座標則不會觸發
@Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.e("Map", "Location changed : Lat: " + location.getLatitude()
+ " Lng: " + location.getLongitude());
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
};
@Override
protected void onDestroy() {
super.onDestroy();
// 別忘了解除註冊,否則會造成記憶體洩漏與電量浪費
if (locationManager != null && locationListener != null) {
locationManager.removeUpdates(locationListener);
}
}
}
main.xml
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:orientation="vertical">
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="經緯度信息:"
android:textColor="#660000"
android:textSize="20sp" />
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.tqmapdemo"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" />
<!-- 網路連線 -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- 定位權限:粗定位(基地台/WiFi)與精定位(GPS) -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
執行結果:

使用 LocationClient 搭配 Bd09ll 座標型別,另外需要在百度開發者平台申請 API Key 並加入 ak 的 meta-data。優點是國內定位精度與覆蓋率較好,且能直接拿到地址描述;缺點是引入 SDK 體積、依賴第三方服務。

同樣需要申請金鑰,座標系統為 CGCS2000。適合需要與其他天地圖服務(電子地圖、影像圖)整合的專案。
座標系統是最大陷阱。GPS 給的是 WGS-84,百度用 BD-09,高德/Google 用 GCJ-02,天地圖用 CGCS2000。混用會導致幾十到幾百公尺的偏移。回報給伺服器前,務必確認雙方約定的是同一套座標系。
原生 API 在新版 Android 上的變化:
toggleGPS() 依賴系統設定 App 的内部 widget,在新版系統上基本已失效;正確做法是跳轉 Settings.ACTION_LOCATION_SOURCE_SETTINGS 讓使用者自行開啟。ACCESS_BACKGROUND_LOCATION,並引入精確度(fine/coarse)選項。
Android 自定義輪播廣告條:復刻淘寶、網易、彩票的 Banner 效果
翻舊專案的時候翻到一個極常用卻容易被當成「不是自定義控制項」的效果——廣告條 / Banner。打開市面上各大 App 的首頁,或多或少都會出現這樣的東西,有些應用甚至同
Android 自訂 ListView 實作下拉刷新與上拉載入更多
下拉刷新、上拉載入更多,幾乎是每個資訊類 App 的標配。與其每次重造輪子,不如把這個行為封裝成一個可直接替換 ListView 的 DynamicListView。
Android 網絡通訊實戰:GET 請求與 POST 請求
做 Android 開發,網絡數據的抓取與提交是家常便飯。一個簡單的口訣可以幫你快速定位場景:獲取數據用 GET 請求,而新增、刪除、修改、查詢等需要改動服務端數據的操作
Android 無障礙服務與自動化點擊技術解析
Android 的無障礙服務原本旨在協助身心障礙或特殊需求使用者操作裝置。開發者在理解其事件監聽與節點操作機制後,可用於自動化測試、輔助操作或特定內部流程。但必須強調,任