我读过文章
通过构造函数将上下文从主活动传递到 Java 类时,获取“此字段泄漏上下文对象”
代码private var mService: RecordService? = null
显示警告“此字段泄漏上下文对象”?为什么?
我认为HomeViewModel
对象销毁后对象会被销毁Activity
,并且mService
也会被释放,为什么Android Studio会显示“此字段泄漏上下文对象”?
class HomeViewModel(private val mApplication: Application, private val mDBVoiceRepository: DBVoiceRepository) : AndroidViewModel(mApplication) {
private var mService: RecordService? = null
private val serviceConnection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, iBinder: IBinder) {
val binder = iBinder as RecordService.MyBinder
mService = binder.service
}
}
fun bindService() {
Intent(mApplication , RecordService::class.java).also { intent ->
mApplication.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
}
}
fun unbindService() {
Intent(mApplication, RecordService::class.java).also { intent ->
mApplication.unbindService(serviceConnection)
mService?.stopForeground(true)
mService?.stopSelf()
}
}
...
}
class RecordService : Service() {
override fun onBind(intent: Intent): IBinder {
return MyBinder()
}
inner class MyBinder : Binder() {
val service: RecordService
get() = this@RecordService
}
...
}
添加的内容
致 AlphaOne:谢谢!
当我使用以下代码时,我仍然收到警告“此字段泄漏上下文对象”,如果需要调用RecordService
该HomeViewModel
怎么办?
class HomeViewModel(private val mApplication: Application,
private val mDBVoiceRepository: DBVoiceRepository,
private var mService: RecordService?) :
AndroidViewModel(mApplication) {
}
还有,下面的代码是 的源代码AndroidViewModel
,看来Android并没有为这个类做额外的工作AndroidViewModel
,似乎是android阻止了显示警告信息。
public class AndroidViewModel extends ViewModel {
@SuppressLint("StaticFieldLeak")
private Application mApplication;
public AndroidViewModel(@NonNull Application application) {
mApplication = application;
}
/**
* Return the application.
*/
@SuppressWarnings({"TypeParameterUnusedInFormals", "unchecked"})
@NonNull
public <T extends Application> T getApplication() {
return (T) mApplication;
}
}
来自官方文档:
ViewModel 绝不能引用视图、生命周期或任何可能持有对活动上下文的引用的类。
由于服务有自己的生命周期并由操作系统管理,因此您不应将其引用保留在 ViewModel 中。
配置更改时,ViewModel 被保留,所以仍然可能有对Service 的引用,会导致内存泄漏。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句