Location Updates every 100 meters using LocationListener

2k views Asked by At

I am new to android. I am trying out a code, to get updates every 100 meters, ie Every 100 meters the location needs to be updated on my apps TextView.

Is this code sufficient enough, cause when I go by car or bike, the TetView is not getting updated properly.(Properly in the sense I get the same location, I need to close the app and re open it to get the new location)

And One more doubt that I have is, is it a good practice to write down the last know location in a file and later display it ?? If I dont have Network connection I can fetch the last known location.

My Code :

public class MainActivity extends Activity implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {


    public static final String TAG=MainActivity.class.getSimpleName();
    UserLocationDetails locationDetails=new UserLocationDetails();
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
    GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    TextView userLocationView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        userLocationView=(TextView) findViewById(R.id.idLocationOfUser);

        mGoogleApiClient=new GoogleApiClient.Builder(this).
                addConnectionCallbacks(this).
                addOnConnectionFailedListener(this).
                addApi(LocationServices.API).build();
        mLocationRequest = LocationRequest.create().setSmallestDisplacement(100)
                .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000); // 1 second, in milliseconds


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if(mGoogleApiClient.isConnected()){
            mGoogleApiClient.disconnect();
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void onConnected(Bundle bundle) {
        Log.i(TAG,"Location Service Connected");
        Location location=LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            Log.e(TAG,"Location is NULL");
        }
        else {
            handleNewLocation(location);
        }


    }

    private void handleNewLocation(Location location) {

        double latitude=location.getLatitude();
        double longitude=location.getLongitude();
        Log.i(TAG,"Latitude : "+location.getLatitude());
        Log.i(TAG,"Longitde : "+location.getLongitude());

        Log.i(TAG, "Location at : " + location.toString());

                locationDetails.setLocationDetailsOfUser(location.toString());

        userLocationView.setText(locationDetails.getLocationDetailsOfUser());
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG,"Location Service Suspended");

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        } else {
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }

    }


    @Override
    public void onLocationChanged(Location location) {
        handleNewLocation(location);
    }
}
1

There are 1 answers

2
Kevin Cronly On
@Override
public void onLocationChanged(Location location) {
    if (location.distanceTo(mCurrentLocation) > 100)
    {
        // do update stuff
        mCurrentLocation = location;
    }
}

Where mCurrentLocation is the last known location.

You can't request location updates based on distance like that.