Android service leaked, although it (presumably) is not working

in onDestroy() I check to see if the service continues to work using the code below. If it is - I disconnect 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 where isServiceRunning returns false, but after onDestroy() an error appears indicating a ServiceConnection leak. Why would that be?

Edit

How I start 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); } 
+4
source share
1 answer

You need to call unbindService() in onDestroy() . Stopping a service will not stop it if it is connected.

In either case, the “ServiceConnection” error message appears because you still have a connected connection to the service.

EDIT: Add Extra Observation

You wrote:

"I check to see if the service continues to work using the code below. It's - I untie and stop it."

This will not prevent a ServiceConnection leak. You need to call unbindService() when your activity shuts down, even if your service is no longer running. Be sure to place the unbindService() call in a try / catch block, because you can get an IllegalArgumentException that can be safely ignored (this means you don't have a connection to the service).

+3
source

All Articles