【发布时间】:2021-06-04 19:19:45
【问题描述】:
帮助!我有泄漏(至少我是这么认为的……)
下面的instance 值是我从静态伴随对象到此类的“端口”。我有一些关于以某种方式使用 applicationContext 的想法(我的 TODO:评论)......因为我收到了这个内存泄漏警告......:
为了避免这个问题,同时在每次调用这些函数时不需要上下文参数(我想以某种方式将上下文存储在类中,并在它死亡时将其处理掉),有什么好的练习解决问题?
...
class Repository private constructor(
var context: Context
)
{
/**
* Repository class, class for all communication between database and external
* sources
* */
private val TAG = javaClass.simpleName
val appDatabase: AppDatabase = AppDatabase.getInstance(context.applicationContext)
//TODO: Test if better with applicationContext?
companion object {
private val TAG = this::class.java.simpleName
@Volatile private var instance:Repository ?=null
fun getInstance(context: Context)= instance
?: synchronized(this){
instance
?:Repository(context).also { instance = it }
}
fun liveDataUserResult(staffId: StaffType=StaffType.DRIVER) =
instance?.liveDataUserResult(staffId = staffId)
fun liveDataDepartmentResult(staffId: StaffType=StaffType.DRIVER) =
instance?.liveDataDepartmentResult(staffId = staffId)
...
fun liveDataGalleryItemSiteNoInUserPath() = instance?.liveDataGalleryItemSiteNoInUserPath()
...
}
fun liveDataGalleryItemSiteNoInUserPath() =
appDatabase.galleryItemDao().liveDataGalleryItemSiteNoInUserPath(allText = context.getString(R.string.repository_all_text))
}
【问题讨论】:
-
已更改上面的 Q 以反映我的答案低于接受的答案。否则也是同样的问题。
标签: android kotlin memory-leaks android-context