Search code examples
androidandroid-activityandroid-serviceandroid-service-binding

Getting "Activity <activityname> has leaked ServiceConnection" despite unbinding it in onDestroy or onPause


I made a custom bound service that I run using startService in my MainActivity, then bind to it. I do the same within one of the other activities. But whenever I quit that activity (and the service keeps running as it was intended to) or even close the application entirely, my get an error along these lines.

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 
...

I unbind the service in both cases in onDestroy, and I have also tried other functions like onUserLeaveHint and onPause but neither seems to work.

Here is my code from the OpenArticle file, where I attempt to unbind my service. Interestingly, the failure message is never displayed in logcat.

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


}

In practice, this doesn't really affect any functionality of the app, but it still seems like I'm doing something wrong.


Solution

  • You should unbind your service in @Override protected void onStop(), because onDestroy might not be called then you leave your activity.