在做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.<init>(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。