绑定服务泄漏内存

前端之家收集整理的这篇文章主要介绍了绑定服务泄漏内存 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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

>是否有泄漏或我是否配置了LeakCanary?
>如何编写不会泄漏的绑定服务?

编码

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

如果我通过以下方式从活动绑定到该服务,则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$0
│                               ~~~~~~
╰→ com.example.serviceleak.LocalService
​     Leaking: YES (RefWatcher was watching this)
最佳答案
我不知道答案是否晚了,但是在阅读了您的问题之后,我还在项目中设置了leakCanary,并发现了此泄漏.我确信这是因为内部的绑定器类持有此处服务的外部类的引用.这就是为什么在泄漏日志中显示LocationService正在泄漏的原因.
我通过@commonsguy here找到了一个解决方案,并通过一个更简单的示例here实施了该解决方案.希望这会有所帮助.继续编码,加油.

猜你在找的Android相关文章