【问题标题】:Getting "Activity <activityname> has leaked ServiceConnection" despite unbinding it in onDestroy or onPause尽管在 onDestroy 或 onPause 中解除绑定,但获取“Activity <activityname> 已泄露 ServiceConnection”
【发布时间】:2016-09-19 02:15:28
【问题描述】:

我创建了一个自定义绑定服务,我在 MainActivity 中使用 startService 运行,然后绑定到它。我在其他活动之一中做同样的事情。但是,每当我退出该活动(并且服务继续按预期运行)甚至完全关闭应用程序时,我都会遇到这些错误。

09-19 01:58:11.660 20750-20750/***.rs E/ActivityThread: Activity ***.rs.OpenArticle has leaked ServiceConnection ***.rs.OpenArticle$1@e2e8d7d that was originally bound here
android.app.ServiceConnectionLeaked: Activity *** has leaked ServiceConnection ***$1@e2e8d7d that was originally bound here
 at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:1092)
 at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:986)
 at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1303)
 at android.app.ContextImpl.bindService(ContextImpl.java:1286)
 at 
...

我在 onDestroy 中解除了这两种情况下的服务绑定,并且我还尝试了其他功能,例如 onUserLeaveHint 和 onPause,但似乎都不起作用。

这是我在 OpenArticle 文件中的代码,我在其中尝试取消绑定我的服务。有趣的是,失败消息永远不会显示在 logcat 中。

@Override
protected void onUserLeaveHint() {
    try {
        unbindService(sConn);
    } catch (RuntimeException e) {
        Log.d("OpenArticle", "Service unbind not successful.");
    }
    super.onUserLeaveHint();


}

实际上,这并不会真正影响应用程序的任何功能,但似乎我仍然做错了什么。

【问题讨论】:

  • 在活动的 onPause() 或 onStop() 方法中执行 unbindService 调用

标签: android android-activity android-service android-service-binding


【解决方案1】:

您应该在@Override protected void onStop() 中取消绑定您的服务,因为 onDestroy 可能不会被调用然后您离开您的活动。

【讨论】:

    猜你喜欢
    • 2010-12-31
    • 2013-11-17
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多