79132200

Date: 2024-10-28 06:02:37
Score: 0.5
Natty:
Report link

I am also confused about this with leakCanary. If you dump the heap and import into Android Studio, you will find that the instance and related object does exist but the AS not showing memory leak("0 classes"??):

image: 28 Allocations here

Now i found out a better way to solve this. Use the static inner class to avoid implicitly holding a outer class intance but hold it with WeakReference:

class MyService : Service() {
    private val binder by lazy { MyServiceBinder(this) }

    override fun onBind(intent: Intent): IBinder {
        return binder
    }
    
    // ...
    
    companion object {
        class MyServiceBinder(service: MyService) : Binder() {
            private val serviceRef: WeakReference<MyService> = WeakReference(service)

            fun getService(): MyService? = serviceRef.get()
        }
    }
}

After doing this, the leakcanary dose not show warnings and the heap dump not shows remaining and other related instances:

image: 10 Allocations here

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: Ercilan