alex
alex

Reputation: 11400

Android Service has leaked even though it is (supposedly) not running

in onDestroy() I check whether the service is still running using the code below. If it is - I unbind and stop it.

public boolean isServiceRunning(Class<?> serviceClass) {
        String serviceClassName = serviceClass.getName();
        final ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);

        for(RunningServiceInfo runningServiceInfo : services){
            if(runningServiceInfo.service.getClassName().equals(serviceClassName)){
                return true;
            }
        }
        return false;
    }

Now I have a situation when isServiceRunning returns false, but after onDestroy() I get an error saying that ServiceConnection has leaked. Why would that be?

Edit:

That's how I start the Service (in onCreate()):

startService(posServiceIntent);
bindService(posServiceIntent, posConn, BIND_AUTO_CREATE);

and

posServiceIntent = new Intent(getApplicationContext(), PositionService.class);

private ServiceConnection posConn = new PosServiceConnection();
public class PosServiceConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "PosServiceBinder connected [name: " + name.toShortString() + "].");
        }
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "PosServiceBinder disconnected [name: " + name.toShortString() + "].");
        }
    }

protected void onDestroy() {
        if(isServiceRunning(PositionService.class)){
            Log.d(TAG, "Stopping PositionService in " + MainActivity.class.getSimpleName() + ".onDestroy()");
            unbindService(posConn);
            stopService(posServiceIntent);
        }

Upvotes: 4

Views: 3567

Answers (1)

David Wasser
David Wasser

Reputation: 95588

You need to call unbindService() in onDestroy(). Stopping the service won't make it stop if it has bound connections.

In any case, the error "ServiceConnection leaked" appears because you still have a bound connection to the service.

EDIT: Add additional observation

You wrote:

"I check whether the service is still running using the code below. If it is - I unbind and stop it"

That won't prevent leaking the ServiceConnection. You need to call unbindService() when your activity shuts down even if your service is no longer running. Make sure to put the call to unbindService() in a try/catch block because it is posible to get an IllegalArgumentException which you can safely ignore (it means you have no connection to the service).

Upvotes: 3

Related Questions