Android服务已经泄露,即使它(据推测)没有运行

Android服务已经泄露,即使它(据推测)没有运行,android,android-service,Android,Android Service,在ondestory()中,我使用下面的代码检查服务是否仍在运行。如果是-我解开并停止它 public boolean isServiceRunning(Class<?> serviceClass) { String serviceClassName = serviceClass.getName(); final ActivityManager activityManager = (ActivityManager) getSystemService(A

ondestory()
中,我使用下面的代码检查服务是否仍在运行。如果是-我解开并停止它

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;
    }


您需要在
ondestory()
中调用
unbindService()
。如果服务已绑定连接,停止服务不会使其停止

在任何情况下,都会出现“ServiceConnection泄漏”错误,因为您仍然有到服务的绑定连接

编辑:添加其他观察结果

你写道:

“我使用下面的代码检查服务是否仍在运行。如果 它是-我解开并停止它“


这无法防止
服务连接泄漏。当活动关闭时,即使服务不再运行,也需要调用
unbindService()
。确保将对
unbindService()
的调用放在try/catch块中,因为它可以得到一个
IllegalArgumentException
,您可以安全地忽略它(这意味着您没有与服务的连接)。

如何实例化该服务?你能粘贴那个代码吗?正确。当活动被销毁时,绑定的服务必须解除绑定。当你这样读的时候,听起来很合乎逻辑,是吗?@tolgap好的,我修复了这个问题,因为你读的时候不清楚,我停止并解除绑定服务。我在我的答案中添加了更多细节,看一看。请确保你在
onDestroy()
中无条件调用
unbindService()
。不要将其放入
if(isServiceRunning())
条件中。
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);
        }