В моем приложении Android I мне нужно создать синглтон-класс и передать контекст android в качестве параметра конструктору:
фрагмент:
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)
}
}
Это правильный путь?