amofasser
amofasser

Reputation: 59

Android location distanceTo within proximity

I'm writing an app where a method is executed based on the users geo location. I'm using an Activity which implements LocationListener. Location latitude and longitude is stored in a database, and whenever the user gets within range of the current location, compared to the location stored, a method is executed.

My problem is that, the methods startTimer(), startTimer() is executed whenever the user moves around whithin the proximity. I want startTimer() to be executed once, whenever the user enters the area, and stopTimer() whenever the user exits the area.

So far i got this, but only seems to work when leaving the area:

@Override
public void onLocationChanged(Location location) {
    longitude = location.getLongitude();
    latitude = location.getLatitude();
    Log.i("", "Latitude: " + latitude);
    Log.i("", "Longitude: " + longitude);
    if(activities != null) {
        for (Activity activity : activities) {
            Location newLocation = new Location(provider);
            newLocation.setLongitude(activity.getLongitude());
            newLocation.setLatitude(activity.getLatitude());

            if(location.distanceTo(newLocation) > 15) {
                activity.setInProximity(false);
                stopTimer(activity.getId());
            }
            if (location.distanceTo(newLocation) <= 15 && !activity.isInProximity()) {
                activity.setInProximity(true);
                startTimer(activity.getId());
            }
        }
    }
}

Upvotes: 0

Views: 140

Answers (1)

mray190
mray190

Reputation: 506

It looks like you are almost there/tried to implement this already - just missed the calls to your function in the first if statement (and also should be an if/else statement)

@Override
public void onLocationChanged(Location location) {
    longitude = location.getLongitude();
    latitude = location.getLatitude();
    Log.i("", "Latitude: " + latitude);
    Log.i("", "Longitude: " + longitude);
    if(activities != null) {
        for (Activity activity : activities) {
            Location newLocation = new Location(provider);
            newLocation.setLongitude(activity.getLongitude());
            newLocation.setLatitude(activity.getLatitude());

            if(location.distanceTo(newLocation) > 15 && activity.isInProximity()) {
                activity.setInProximity(false);
                stopTimer(activity.getId());
            }
            else if (location.distanceTo(newLocation) <= 15 && !activity.isInProximity()) {
                activity.setInProximity(true);
                startTimer(activity.getId());
            }
        }
    }
}

where

void setInProximity(boolean status)

and

boolean isInProximity()

should be getters/setters to a private boolean data member of the Activity class you iterate through

Upvotes: 1

Related Questions