1

I am using google's fusedlocationapi in android for getting user's current latitude and longitude, now according to my use case i only want to get user's current location only when user clicks on a button, now i thought that instead of requesting for location updates again and again between a time interval i can use something different so that my user's battery will not get drained much, i searched a lot of posts on SO and on other communities also but didn't find anything useful. Now can anybody please tell me how can i find something that will work for my use case.

Prakash Kumar
  • 829
  • 1
  • 15
  • 32

1 Answers1

1

You can just remove the location updates when you get a location

  LocationRequest mLocationRequest = new LocationRequest();
  mLocationRequest.setInterval(1000);
  mLocationRequest.setFastestInterval(1001);
  mLocationRequest.setNumUpdates(1);
  mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
  LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, new com.google.android.gms.location.LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
              // save your location here

            }
        });
Ahmed Abidi
  • 1,047
  • 12
  • 24
  • Yes i thought about the same thing but the problem is when user clicks again on the button then i want to fetch updated location but according to your code it will give last old location because as now you are not requesting for location updates. Please correct me if i am thinking in wrong direction. – Prakash Kumar Oct 11 '16 at 14:47
  • When the user clicks again, you just start this function again and save the updated location – Ahmed Abidi Oct 11 '16 at 14:53
  • yes but it takes mostly about 5 secs of time to fetch the location but i don't want that much delay, how can in real apps(e.g Zomato, etc) when you click on auto-detect they fetch location instantly ?? there is no time delay ?? – Prakash Kumar Oct 11 '16 at 14:56
  • i am waiting for your response @Ahmed Abidi – Prakash Kumar Oct 14 '16 at 14:22
  • I suspect the Zomato app is requesting continous location updates with PRIORITY_NO_POWER in onResume. – zyamys May 18 '17 at 23:55