![](/img/trans.png)
[英]locationManager.getLastKnownLocation returns null after request
[英]LocationManager returns null longitude with getLastKnownLocation in Android
我有一個代碼應該返回用戶位置,但經度保持返回null
,因此我的應用程序不斷崩潰。 我該如何防止這種情況?
//get the user longitude and latitude
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Geocoder geocoder; //return meaningful data from user location
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
addresses = geocoder.getFromLocation(latitude, longitude, 1);
address = addresses.get(0).getAddressLine(0);
city = addresses.get(0).getLocality();
添加一張支票。
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);
}
}
免責聲明請注意,這只是所需代碼的一部分,並有助於實施位置服務。 在不使用資源時需要釋放資源,並且需要在整個應用程序的程序流程中管理項目的所有其他方面的位置服務的使用。
查看獲取最新已知位置或Android位置API - 教程或Android - 基於位置的服務 ,以更全面地實施位置服務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.