Search code examples
androidserviceandroid-serviceandroid-ondestroy

I cannot stop Location service from my fragment. How can stop it?


I start my service from onCreateView like

getActivity().startService(new Intent(getActivity(), LocationService.class));

And I try to stop my service like this

    @Override
public void onDestroyView() {
    getActivity().stopService(new Intent(getActivity(),LocationService.class));
    super.onDestroyView();
}

@Override
public void onStop() {
    getActivity().stopService(new Intent(getActivity(), LocationService.class));
    super.onStop();
}

@Override
public void onDestroy() {
    getActivity().stopService(new Intent(getActivity(), LocationService.class));
    super.onDestroy();
}

Solution

  • I didn't used LocationManager in my service class but I used GoogleApiClient and after a lot try I used following code in onDestroy(). Finally, it is done.

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (googleApiClient != null && googleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
        }
    }