Enr*_*ico 5 android android-service android-service-binding leakcanary
我根据 Android 文档编写了一个基本的绑定服务,但 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
}
}
Run Code Online (Sandbox Code Playgroud)
如果我从一个活动绑定到服务如下,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
}
}
}
Run Code Online (Sandbox Code Playgroud)
?
?? 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
550 次 |
| 最近记录: |