我正在創建一個應用程序,當用戶單擊按鈕時只檢查位置。android getLastKnownLocation()返回總是返回空
這裏是我的代碼,當我打電話getLastKnownLocation返回null,即使我打電話requestLocationUpdates:
public void main(String[] args, int iteration, Context context){
Criteria criteria = new Criteria();
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
LocationListener loc_listener = new LocationListener() {
public void onLocationChanged(Location l) {
}
public void onProviderEnabled(String p) {}
public void onProviderDisabled(String p) {}
public void onStatusChanged(String p, int status, Bundle extras) {}
};
String bestProvider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
Location location = locationManager.getLastKnownLocation(bestProvider);
location = locationManager.getLastKnownLocation(bestProvider);
double lat;
double lon;
try {
lat = location.getLatitude();
lon = location.getLongitude();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
Log.i("results:", String.valueOf(lat) + " " + String.valueOf(lon) + " 10NN");}}
設備上的定位服務已啓用。 非常感謝!
LastKnownLocation返回最後一個已知的修復。所以它有可能是空的。嘗試看看這裏http://stackoverflow.com/questions/7423624/how-reliable-is-locationmanagers-getlastknownlocation-and-how-often-is-it-updat – alekz
我試圖requestLocationUpdates,它並沒有實際更新最後一個我知道的位置。 –
你有沒有找到解決方案 – Questioner