1. 程式人生 > >Android 解決 GetLastKnownLocation(provider) = null

Android 解決 GetLastKnownLocation(provider) = null

事情的起因就是我用系統的GetLastKnownLocation輸出結果永遠是null。後來看大家說這個方法在室內90%都不管用。

於是查了國內各大網站給出了兩個解決辦法:

1.while(GetLastKnownLocation(provider) = null){

    GetLastKnownLocation = null

}

2.locationManager.setTestProviderEnabled(provider1, false);

然而這兩種方法並沒能解決我的問題。只是瘋狂在while裡迴圈,知道我的App崩潰。。。

最後查詢StackOverflow得到解決辦法。

用如下辦法獲取Last Location

LocationManager mLocationManager;Location myLocation = getLastKnownLocation();privateLocation getLastKnownLocation(){
    mLocationManager =(LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);List<String> providers = mLocationManager.getProviders(true);Location bestLocation 
=null;for(String provider : providers){Location l = mLocationManager.getLastKnownLocation(provider);if(l ==null){continue;}if(bestLocation ==null|| l.getAccuracy()< bestLocation.getAccuracy()){// Found best last known location: %s", l); bestLocation = l;}}return bestLocation;}

結果很成功。

激動之餘記錄一下,並分享給大家。