Android lateinit 服务绑定的上下文泄漏
Android Context leak for lateinit service binding
所以我创建了一项服务,方法如下:https://developer.android.com/guide/components/bound-services
我在视图模型中绑定服务。
现在 linter 给我以下警告:
错误:该字段
泄漏上下文对象 [StaticFieldLeak]
lateinit var positionManager: PositionManager
如何解决?
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)
}
}
改为使用可空字段,并在 stopService
方法中将其设置为空。
解决方案是将服务置于弱引用中:
lateinit var positionManager: WeakReference<PositionManager>
问题是视图模型持有对服务的引用。如果要销毁视图模型,服务的引用可能会阻止 GC 释放其内存 - 导致泄漏。有关详细信息,请参阅此 post:
https://medium.com/@zhangqichuan/memory-leak-in-android-4a6a7e8d7780
所以我创建了一项服务,方法如下:https://developer.android.com/guide/components/bound-services
我在视图模型中绑定服务。
现在 linter 给我以下警告:
错误:该字段 泄漏上下文对象 [StaticFieldLeak] lateinit var positionManager: PositionManager
如何解决?
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)
}
}
改为使用可空字段,并在 stopService
方法中将其设置为空。
解决方案是将服务置于弱引用中:
lateinit var positionManager: WeakReference<PositionManager>
问题是视图模型持有对服务的引用。如果要销毁视图模型,服务的引用可能会阻止 GC 释放其内存 - 导致泄漏。有关详细信息,请参阅此 post:
https://medium.com/@zhangqichuan/memory-leak-in-android-4a6a7e8d7780