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); }
source share