在onDestroy()
我使用下面的代码检查服务是否仍在运行。如果是 - 我解除绑定并停止它。
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;
}
现在我有一种情况,当isServiceRunning
返回 false 时,但是在onDestroy()
我收到一个错误说 ServiceConnection 已泄漏之后。为什么会这样?
编辑:
这就是我开始Service
(in onCreate()
)的方式:
startService(posServiceIntent);
bindService(posServiceIntent, posConn, BIND_AUTO_CREATE);
和
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);
}