2015-09-09 111 views
-1

在我的應用程序中,我從網絡獲取位置,如果網絡不可用,我的代碼將返回最後一個位置,在這兩種情況下我都想知道位置是當前位置還是最後一個已知位置。可有人請告訴我怎麼知道this.Thanks提前Android:如何檢查位置是當前位置還是最後一個已知位置

public Location getLocation() { 
    try { 
     locationManager = (LocationManager)mContext.getSystemService(LOCATION_SERVICE); 
     // getting network status 
     isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (isNetworkEnabled) { 
       locationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       if (locationManager != null) { 
        location = locationManager 
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (location != null) { 
         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 
        } 
       } 
      } 

      else{ } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return location; 
} 

public double getLatitude(){ 
    if(location != null){ 
     latitude = location.getLatitude(); 
    }  
    return latitude; 
} 

public double getLongitude(){ 
    if(location != null){ 
     longitude = location.getLongitude(); 
    } 
     return longitude; 
} 

回答

2

你需要做到這一點使用SharedPrefences

存放在共享偏好的當前位置(經度和緯度高達約5位小數)。將新位置與共享首選項中的位置進行比較。如果它們相同,則新位置是最後一次已知位置,如果不是新位置是新位置,則將其再次保存在共享首選項中。

相關問題