LocationManager.getLastKnownLocation() 僅返回**上次已知位置**,若設備近期未定位(如剛啟動、室內、GPS 未熱啟動),返回 **null**。
public class GpsActivity extends Activity implements LocationListener {
LocationManager locationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// 1. 先嘗試獲取最後已知位置(可能為 null)
Location lastLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (lastLoc != null) {
updateUI(lastLoc);
}
// 2. 請求位置更新(最小時間 0ms,最小距離 0m,即盡快回調)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public void onLocationChanged(Location location) {
if (location != null) {
updateUI(location); // 獲取到新位置
// 如需單次定位,可在此調用 removeUpdates(this)
}
}
@Override public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override public void onProviderEnabled(String provider) {}
@Override public void onProviderDisabled(String provider) {}
private void updateUI(Location loc) {
double lat = loc.getLatitude();
double lng = loc.getLongitude();
runOnUiThread(() -> textView.setText(String.format("Lat: %.6f, Lng: %.6f", lat, lng)));
}
@Override
protected void onDestroy() {
super.onDestroy();
locationManager.removeUpdates(this); // 防洩漏
}
}
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
運行時請求 ACCESS_FINE_LOCATION,用戶拒絕則無法定位。
NETWORK_PROVIDER 融合定位。FusedLocationProviderClient 更省電、準確。