在onDestroy()
我使用下面的代码检查服务是否仍在运行。如果是 - 我解开并停止它。虽然(假定)没有运行,但Android服务已经泄漏
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
(在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);
}
你如何实例化服务?你能粘贴该代码吗? – tolgap
已添加@tolgap代码。 – alex