Should I unregister locationcallback for fusedLocationProviderClient?

I am trying to get the location of a user in the background using a service. I am using FusedLocationProviderClient to complete this task, and I am doing all this in my service class.

I provide the user with two buttons with the name "Yes" and "No." When the user clicks โ€œYesโ€, I start the service, and if the user clicks โ€œNoโ€, I stop the service.

An actual problem occurs when the user clicks the Yes button and then clicks No. Let me provide a complete script step by step.

  • Click "Yes" to get started, and I am requesting location updates using FusedLocationProviderClient.
  • Now the user clicks the No button, so I call the stopervice method to stop my service.

Now the problem is that my service is stopping, but still I get a list of addresses of users that I do not want.

So, I wonder how this is possible. Is there a need to unregister locationcallback?

GpsPingService.java

@Override public int onStartCommand(Intent intent, int flags, int startId) { Log.e("JK-->>", "Gpsping Service onstartcommand!"); try { locationRequest = new LocationRequest() .setInterval(1000) .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY) .setFastestInterval(1000); locationCallback = new LocationCallback() { @Override public void onLocationResult(LocationResult locationResult) { Log.e("JK-->>", "location updated by gpsping service-->> " + locationResult.getLastLocation().getLatitude() + " " + locationResult.getLastLocation().getLongitude()); Toast.makeText(getApplicationContext(), "Location changed!", Toast.LENGTH_SHORT).show(); } }; fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getApplicationContext()); fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper()); } catch (Exception e) { Log.e("JK-->>Gpsping-->> ", e.getMessage()); } return START_STICKY; } 
+1
source share
1 answer

You need to cancel the callback so that you don't get the result every time. You can use:

 fusedLocationProviderClient.removeLocationUpdates(locationCallback); 

You need to make the scope of the locationCallback class so that you can call it outside of onStartCommand()

+1
source

All Articles