片段中的绑定服务导致错误

时间:2014-01-29 21:11:20

标签: android android-fragments connection android-service

我在ViewPager中有FragmenActivity,里面有3个页面。所有这些都将服务绑定到数据。当我在启动函数中关闭所有片段中的活动时出错。在那里我绑定了那些碎片。

01-29 21:42:39.394 69

45-6945/ E/ActivityThread﹕ Activity Activity has leaked ServiceConnection Fragment$1@419ae7c8 that was originally bound here
    android.app.ServiceConnectionLeaked: Activity Activity has leaked ServiceConnection BillFragment$1@419ae7c8 that was originally bound here
            at android.app.LoadedApk$ServiceDispatcher.<init>(LoadedApk.java:974)
            at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:868)
            at android.app.ContextImpl.bindService(ContextImpl.java:1762)
            at android.app.ContextImpl.bindService(ContextImpl.java:1751)
            at android.content.ContextWrapper.bindService(ContextWrapper.java:480)
            at Fragment.onStart(Fragment.java:127)

代码,片段:

@Override
public void onStart() {
    super.onStart();
    // Bind to the service
    getActivity().bindService(new Intent(getActivity(), Service.class), mConnection, Context.BIND_AUTO_CREATE);
}

1 个答案:

答案 0 :(得分:0)

您必须在onStop()中取消绑定服务。向您Fragment添加另一种方法,如下所示。

@Override
public void onStop() {
    getActivity().unbindService(mConnection);
    super.onStop();
}

否则托管活动将泄露服务连接。