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已泄露.那为什么会这样?
编辑:
这就是我启动服务的方式(在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); }解决方法 您需要在onDestroy()中调用unbindService().如果绑定绑定,则停止服务不会使其停止.
在任何情况下,都会出现错误“ServiceConnection泄露”,因为您仍然具有与服务的绑定连接.
编辑:添加额外的观察
你写了:
“I check whether the service is still running using the code below. If
it is – I unbind and stop it”
这不会阻止ServiceConnection泄露.即使您的服务不再运行,您也需要在活动关闭时调用unbindService().确保将调用unbindService()放在try / catch块中,因为它可以获得IllegalArgumentException,您可以放心地忽略它(这意味着您没有连接到该服务).
总结以上是内存溢出为你收集整理的Android服务已经泄露,即使它(据说)没有运行全部内容,希望文章能够帮你解决Android服务已经泄露,即使它(据说)没有运行所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)