首先自定义一个application,继承Application,并在AndroidManifest.xml文件中配置它。
class TvApplication : Application() {
companion object {
@Volatile
var context: Application? = null
private set
fun getContext(): Context {
return context ?: throw IllegalStateException("Application context not initialized yet.")
}
}
override fun onCreate() {
super.onCreate()
context = this
}
}
使用示例
val packageManager = TvApplication.getContext().packageManager
?: throw IllegalStateException("PackageManager is null. Ensure that the application context is initialized.")