2013-03-27 233 views
2

我嘗試獲取GPS數據。但GPS數據返回空值。當我看,下面的'位置'返回null,所以我無法獲得GPS數據。
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);從Android手機獲取GPS數據

我的代碼如下;

protected LocationManager locationManager; 

public GPSTracker(Context context) { 
    this.mContext = context; 
    getLocation(); 
} 

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) 
     { 

     } 
     else if (!isGPSEnabled && !isNetworkEnabled) 
     { 
         } 
     else 
     { 
      this.canGetLocation = true; 

      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(); 
         } 
        } 
       } 
      } 

我等你的幫忙。謝謝

+0

我發現有時函數getLastKnownLocation()可以返回null,如果用戶還沒有激活/使用位置源一段時間。最好像你一樣檢查。如果它爲空,則必須等待下一個位置更新 – chopchop 2013-03-27 22:39:38

+0

或者設置requestSingleUpdate或requestLocationUpdates以自行打開GPS。 – 2013-03-27 22:52:45

+0

如果提供者當前被禁用,則返回null。我使用GPS_PROVIDER。我如何啓用? – efrahimates 2013-03-27 23:11:07

回答

1

你在清單中設置了這些嗎?

<uses-permission android:name="android.permission.INTERNET"></uses-permission> 
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> 
+0

是的,我已經設置了清單中的所有權限。 – efrahimates 2013-03-27 22:50:05

1

我改變了下面的代碼,然後成功。

String bestProvider = locationManager.getBestProvider(criteria, false); 

locationManager.requestLocationUpdates(bestProvider, MIN_TIME_BW_UPDATES,  
MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
if (locationManager != null) { 

location = locationManager.getLastKnownLocation(bestProvider); 

    if (location != null) 
    { 
latitude = location.getLatitude(); 
longitude = location.getLongitude(); 
} 
}