Android应用开发——service连接泄露异常:android.app.ServiceConnectionLeaked: that was originally bound here

在做service开发过程中,大部分可能会遇到以下异常,该异常仅通过log输出,并不会导致app crash。

E/ActivityThread: Activity com.example.image.all_samples.Main2Activity has leaked ServiceConnection com.example.image.all_samples.Main2Activity$5@d124870 that was originally bound here
                   android.app.ServiceConnectionLeaked: Activity com.example.image.all_samples.Main2Activity has leaked ServiceConnection com.example.image.all_samples.Main2Activity$5@d124870 that was originally bound here
                       at android.app.LoadedApk$ServiceDispatcher.(LoadedApk.java:1369)
                       at android.app.LoadedApk.getServiceDispatcher(LoadedApk.java:1264)
                       at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1454)
                       at android.app.ContextImpl.bindService(ContextImpl.java:1426)
                       at android.content.ContextWrapper.bindService(ContextWrapper.java:636)
                       at com.example.image.all_samples.Main2Activity$3.onClick(Main2Activity.java:53)
                       at android.view.View.performClick(View.java:5724)
                       at android.view.View$PerformClick.run(View.java:22572)
                       at android.os.Handler.handleCallback(Handler.java:751)
                       at android.os.Handler.dispatchMessage(Handler.java:95)
                       at android.os.Looper.loop(Looper.java:154)
                       at android.app.ActivityThread.main(ActivityThread.java:6259)
                       at java.lang.reflect.Method.invoke(Native Method)
                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:913)
                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:803)

异常原因:
比较简单,一般为在activity退出时未调用unbindService导致,只需要添加unbindService接口即可。

进一步思考:android系统是如何检测到给泄漏的呢。
很容想到bindService时,是通过当前activity的context进行bind的,所以service的生命周期应该是同改activity关联,进一步验证,bindService时通过application的context进行bind,退出当前activity时,不会报上面的异常错误,基本可以证明service的生命周期同bindService时依赖的context相关,所以如果需要一个不依赖于具体activity生命周期的service,需要用application的context进行bind。

你可能感兴趣的:(Android应用开发)