Search code examples
androidkotlinserviceviewmodel

Android Context leak for lateinit service binding


So i created a service, by following this: https://developer.android.com/guide/components/bound-services

I bind the service in a viewmodel.

Now the linter gives me the following warning:

Error: This field leaks a context object [StaticFieldLeak] lateinit var positionManager: PositionManager

How to resolve this?


   var mBound = false
   lateinit var positionManager: PositionManager

   private val connection = object : ServiceConnection {
       override fun onServiceConnected(className: ComponentName, service: IBinder) {
           val binder = service as PositionManager.LocalBinder
           if (!mBound) {
               positionManager = binder.getService()
               mBound = true
           }
       }

       override fun onServiceDisconnected(arg0: ComponentName) {
           mBound = false
       }
   }

   public fun startServices(context: Context?) {
       Intent(context, PositionManager::class.java).also { intent ->
           context?.bindService(intent, connection, Context.BIND_AUTO_CREATE)
       }
   }

   public fun stopService(context: Context?){
       if(mBound){
           context?.unbindService(connection)
       }
   }


Solution

  • The solution was to put the service in a weak ref:

    lateinit var positionManager: WeakReference<PositionManager>
    

    The issue was that the viewmodel was holding a reference to the service. If the viewmodel is to be destroyed, the ref to the service might keep the GC from freeing its memory - causing a leak. See this post for more info:

    https://medium.com/@zhangqichuan/memory-leak-in-android-4a6a7e8d7780