【发布时间】:2021-07-17 00:28:00
【问题描述】:
所以我创建了一个服务,按照这个: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)
}
}
【问题讨论】:
标签: android kotlin service viewmodel