添加支票。
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
至於爲什麼它沒有返回值,你需要添加一些日誌記錄。
更完整的解決方案試試這個:
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get destination from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
// Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(
LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
// Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(
LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
在此實現,這是從一個類的方法,我從我的活動調用。隨着代碼需要釋放資源後,他們不再需要。
例如:
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(LocFinder.this);
}
}
免責聲明請注意,這是需要的代碼中的一部分,並且在實施定位服務,以協助。資源在不被使用時需要被釋放,位置服務的使用與項目的所有其他方面一樣需要在整個應用程序的流程中進行管理。
查看Getting the Last Known Location或Android Location API - Tutorial或Android - Location Based Services以更全面地實施位置服務。
請發佈您的錯誤堆棧跟蹤 – Prudhvi
double longitude = location.getLongitude(); – Blaze
你的位置是空的,而不是你的經度。 – Zircon