gpt4 book ai didi

android - 在构造函数中使用 Android 上下文作为参数创建单例类

转载 作者:行者123 更新时间:2023-12-04 15:35:16 25 4
gpt4 key购买 nike

在我的 Android I 应用程序中,我需要创建单例类并将 android 上下文作为参数传递给构造函数:

fragment :

class RecognizedCheckDataService private constructor(context: Context) {
private var context: Context? = null

init { // default constructor
this.context = context
recognizedCheckDataDir =
AndroidFileUtil.getInternalStoragePath(context, RECOGNIZED_CHECK_DATA)
}

companion object {
var recognizedCheckDataDir: File? = null
private val RECOGNIZED_CHECK_DATA = "RECOGNIZED_CHECK_DATA"
private var instance: RecognizedCheckDataService? = null

private val TAG = RecognizedCheckDataService::class.java.name

@Synchronized
fun getInstance(context: Context): RecognizedCheckDataService {
if (instance == null) {
instance = RecognizedCheckDataService(context)
}
return instance as RecognizedCheckDataService
}

fun deleteRecognizedCheckDataDir(): Boolean {
try {
// first check is exist and then delete
FileUtils.deleteDirectory(recognizedCheckDataDir);
return true
} catch (e: IOException) {
return false
}
}
}
}

并使用:

class Main : Application() {
companion object {
private lateinit var appContext: Context

fun getAppContext(): Context {
return appContext
}

}

override fun onCreate() {
super.onCreate()
//Debug.d(TAG, "onCreate: ENTRY_POINT")
init()
}

private fun init() {
appContext = this
RecognizedCheckDataService.getInstance(appContext)
}
}

这是正确的方法吗?

最佳答案

我想这对你有帮助。

class Singleton {
var mContext: Context

constructor(context: Context) {
mContext = context
}

companion object {
private var instance: HttpClientService? = null
fun getInstance(context: Context): HttpClientService {
if (instance == null) {
instance = HttpClientService(context)
}

return instance!!
}
}
}

关于android - 在构造函数中使用 Android 上下文作为参数创建单例类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59984126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com