Should i need to unregister locationcallback for fusedLocationProviderClient?

谁都会走 提交于 2019-12-24 11:29:49

问题


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;
    }

回答1:


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()



来源:https://stackoverflow.com/questions/49115524/should-i-need-to-unregister-locationcallback-for-fusedlocationproviderclient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!