Andrain
Andrain

Reputation: 910

Android: how to check the location is current location or last known location

In my app I getting location from network and if network is not not available my code returns the last location, In both the cases I want to know whether the location is current location or it is the last known location. can somebody please show me how to know this.Thanks in advance

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

Upvotes: 0

Views: 644

Answers (1)

kgandroid
kgandroid

Reputation: 5595

You need to achieve this using SharedPrefences

Store the current location(the latitude and longitude upto approx 5 decimal places) in shared preferences.Compare the new location with that in the shared preferences.If they are same,then the new location is your last known location,if not the new location is the new one,save it again in your shared preference.

Upvotes: 2

Related Questions