stopService doesn't stop's my service… why

2019-01-17 20:53发布

i have a background service on my android APP that is getting my GPS position and sending it to a remote db. It work's fine.

The problem is when i want to stop the service.... it doesn't stops :S. Also no exception or errors on logcat have appeared... it simply doesn't stops.

this is the code to start my srvice (with a button):

startService(new Intent(GPSLoc.this, MyService.class)); //enciendo el service

this is the code where I stop it (on the onactivityresult method):

stopService(new Intent(GPSLoc.this, MyService.class));

I have been debugged the app, and i checked that the stopService codeline has been called every time that i debugged it, but it doesn't stops......

i am sure that it's not stopped cause on my database i still recive gps positions from the emulator when i have press the button to stop the service.

what i am doing bad?

10条回答
祖国的老花朵
2楼-- · 2019-01-17 21:37

it could be perhaps that you are creating a new Intent everytime you call the stop service.

stopService(new Intent(GPSLoc.this, MyService.class));

perhaps try :

Intent intnet = new Intent(GPSLoc.this, MyService.class); // create el service

startService(intenet); 
stopService(intent);
查看更多
淡お忘
3楼-- · 2019-01-17 21:38

Have you implemented onDestroy()? If not, I believe that might be the solution - and you stop your Timer or whatever you're using to run the service within onDestroy().

A service can be stopped by calling its stopSelf() method, or by calling Context.stopService().

See this link for some more information.

查看更多
4楼-- · 2019-01-17 21:38

i am sure that it's not stopped cause on my database i still recive gps positions from the emulator when i have press the button to stop the service.

You probably are not unregistering your LocationListener.

查看更多
beautiful°
5楼-- · 2019-01-17 21:39

I had the same problem. I found that if the service has GoogleApiClient connected and still get location update, the stopService() has totally no effect, the service's industry() was not called. To fix the problem, I created a function to stop the location service in the service code. Call the stopLocationService() from the activity, and then call stopService. Here is the code example:

public class myLocationService extends Service{
...

    public void stopLocationUpdates() {

        LocationService.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);       
        mGoogleApiClient.disconnect();

    }
    ...
} 

In activity,

{
    ...
    if(mService != null && isBound) {

        mService.stopLocationUpdates();
        doUnbindService();
        stopService(new Intent(this,   myLocationService.class));

     }
     ...
} 
查看更多
登录 后发表回答