2017-04-13 53 views
0

我試圖通過位置管理器獲取用戶位置,但位置始終返回null。我也要求用戶打開GPS。Android獲取位置管理器的經緯度

這是我的代碼:

int permisioncheck = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION); 

    if(permisioncheck == 0){ 

     lm = (LocationManager)getContext().getSystemService(Context.LOCATION_SERVICE); 

     List<String> providers = lm.getProviders(true); 

     Location bestLocation = null; 

     for (String provider : providers) { 
      Location location = lm.getLastKnownLocation(provider); 
      if (location == null) { 
       continue; 
      } 

      if (bestLocation == null || location.getAccuracy() < bestLocation.getAccuracy()) { 
       // Found best last known location: %s", l); 
       bestLocation = location; 
      } 
     } 

     if(bestLocation == null){ 
      System.out.println("is NULL!"); 
     } 
    }else{ 

     ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1); 
    } 

我希望有人可以幫助我找到錯誤,謝謝。

+0

@OusmaneMahyDiaw還有什麼我必須添加到我的問題?實際上這是我所有的代碼 –

回答

3

「錯誤」是假設getLastKnownLocation()將返回Location。通常,它將返回null。使用getLastKnownLocation()作爲可能的優化,但除此之外,您需要requestLocationUpdates(),然後使用onLocationChanged()方法中的位置。

有關更多信息,請參見this sample projectthe documentation