Search code examples
javaandroidfusedlocationproviderapi

Should i need to unregister locationcallback for fusedLocationProviderClient?


i am trying to get user's location in background using service. I am using FusedLocationProviderClient for complete this task and i am doin all this thing in my service class.

I am providing two button named "Yes" and "No" to user. When user press "Yes" i am starting service and if user press "No" i stop the service.

Actual problem arise when once user press "Yes" button and then press "No".let me provide complete scenario step by step.

  1. User press "Yes" button so i am starting service and in that i am requesting location updates using FusedLocationProviderClient.
  2. Now user press "No" button so i am calling stopservice method for stopping my service.

Now problem is my service gets stopped but still i am getting locationupdates of users which i don't want.

So, i am wondering that how is it possible. is there any 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;
    }

Solution

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

    fusedLocationProviderClient.removeLocationUpdates(locationCallback);
    

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