绑定服务泄漏内存

Bound service leaks memory

我写了一个基本的 bound service based on the Android documentation,但是 LeakCanary 告诉我服务正在泄漏。

  1. 是否存在泄漏或我是否错误配置了 LeakCanary?
  2. 如何编写不泄漏的绑定服务?

代码

class LocalService : Service() {

  private val binder = LocalBinder()
  private val generator = Random()

  val randomNumber: Int
    get() = generator.nextInt(100)

  inner class LocalBinder : Binder() {
    fun getService(): LocalService = this@LocalService
  }

  override fun onBind(intent: Intent): IBinder {
    return binder
  }

  override fun onDestroy() {
    super.onDestroy()
    LeakSentry.refWatcher.watch(this) // Only modification is to add LeakCanary
  }
}

如果我按如下方式从 activity 绑定到服务,LeakCanary 会检测到服务已泄漏

class MainActivity: Activity() {

  private var service: LocalService? = null
  private val serviceConnection = object: ServiceConnection {
    override fun onServiceConnected(name: ComponentName?, binder: IBinder?) {
      service = (binder as LocalBinder).getService()
    }
    override fun onServiceDisconnected(name: ComponentName?) {
      service = null
    }
  }

  override fun onStart() {
    super.onStart()
    bindService(Intent(this, LocalService::class.java), serviceConnection, BIND_AUTO_CREATE)
  } 

  override fun onStop() {
    super.onStop()
    service?.let {
      unbindService(serviceConnection)
      service = null
    }
  }
}
┬
├─ com.example.serviceleak.LocalService$LocalBinder
│    Leaking: NO (it's a GC root)
│    ↓ LocalService$LocalBinder.this[=12=]
│                               ~~~~~~
╰→ com.example.serviceleak.LocalService
​     Leaking: YES (RefWatcher was watching this)

我不知道现在回答是否晚了,但在阅读了你的问题后,我还在我的项目中设置了 leakCanary 并发现了这个漏洞。我确信这是因为内部活页夹 class 持有外部 class 的引用,这里是服务。这就是为什么在您的泄漏日志中显示 LocationService 正在泄漏的原因。 我找到了@commonsguy here and implemented the solution with a bit simpler example here 的解决方案。希望这可以帮助。继续编码,保持幸福。