在另一个模块中使用应用程序上下文



我有一个像FileLog这样的单例类,我想在它的一个方法中创建一个文件,并且需要一个上下文来完成它。我的问题是,FileLog类被放置在另一个模块,我没有访问应用程序模块上下文。你能告诉我如何使用Hilt或其他方式访问上下文吗?

编辑 --------------------------& , gt的在祝辞祝辞祝辞& lt; & lt; & lt; & lt; & lt; & lt ;--------------------------

这是我的类,它是一个单例。如果我向它传递一个上下文,我将面临内存泄漏。我只需要一个方法中的context我不想把context作为参数传递给那个方法。如果我访问一个扩展Application()的类,并且在其中有一个静态上下文,我可以在FileLog类方法中使用它。

open class FileLog private constructor(context: Context) {
private lateinit var streamWriter: OutputStreamWriter
private var dateFormat: SimpleDateFormat? = null
private var currentFile: File? = null
private var networkFile: File? = null
private var tonlibFile: File? = null
private var initied = false
private var context: Context = context
companion object {
lateinit var INSTANCE: FileLog
@Synchronized
fun getInstance(context: Context): FileLog {
if (!Companion::INSTANCE.isInitialized) {
INSTANCE = FileLog(context)
}
return INSTANCE
}
}
fun initFileLog(context: Context) {
Log.e("FileLog", "create file")
if (initied) {
return
}
dateFormat = SimpleDateFormat("dd_MM_yyyy_HH_mm_ss", Locale.US)
try {
val sdCard: File = context.getExternalFilesDir(null)
?: return
val dir = File(sdCard.absolutePath + "/logs")
dir.mkdirs()
currentFile =
File(dir, dateFormat?.format(System.currentTimeMillis()).toString() + ".txt")
} catch (e: Exception) {
e.printStackTrace()
}
}   

您的记录器实际上需要Context吗?不,它需要一个File的外部文件目录。

fun initFileLog(sdCard: File) {
Log.e("FileLog", "create file")
if (initied) {
return
}
dateFormat = SimpleDateFormat("dd_MM_yyyy_HH_mm_ss", Locale.US)
try {
val dir = File(sdCard.absolutePath + "/logs")
...
}
}}

您可以从app模块中提供这样的File

作为一个经验法则,你应该在你的模块中避免Android依赖,这使得它们可以在更简单的环境中进行测试。

我认为你也可以使用对象类因为它只包含一个实例

object FileLos{
private lateinit var streamWriter: OutputStreamWriter
private var dateFormat: SimpleDateFormat? = null
private var currentFile: File? = null
private var networkFile: File? = null
private var tonlibFile: File? = null
private var initied = false
fun initFileLog(context: Context) {
Log.e("FileLog", "create file")
if (initied) {
return
}
dateFormat = SimpleDateFormat("dd_MM_yyyy_HH_mm_ss", Locale.US)
try {
val sdCard: File = context.getExternalFilesDir(null)
?: return
val dir = File(sdCard.absolutePath + "/logs")
dir.mkdirs()
currentFile =
File(dir, dateFormat?.format(System.currentTimeMillis()).toString() + ".txt")
} catch (e: Exception) {
e.printStackTrace()
}
}}

你可以在app类中公开应用上下文,而不是将上下文传递给方法:

class App : Application() {
companion object {
val context: App
get() = contextReference.get()!! as App
}
}

,并像这样使用:

App.context.getExternalFilesDir(null)

最新更新