问题描述
我正在尝试根据here使用的指南来使用CompanionDeviceManager。
在尝试在实例上调用关联时,尽管出现以下异常:
java.lang.classCastException: android.app.ContextImpl cannot be cast to android.app.Activity
我正在通过getSystemService(CompanionDeviceManager.class)
在活动中获得CompanionDeviceManager的实例,我尝试将其移动,甚至移至onCreate,但没有任何变化,始终是相同的异常。我什至尝试几次重新安装该应用程序,但均未成功。我该如何解决?
解决方法
在我的情况下,我遇到了相同的错误,并发现这是因为我正在更改attachBaseContext中的上下文(出于动态更改语言的目的)。我正在使用:
super.attachBaseContext(newBase.createConfigurationContext(config))
似乎CompanionDeviceManager需要将创建它的上下文作为一个Activity(可能是因为它正在创建对话框)。
我将使用直接作为AppCompatActivity的后代的活动来仔细检查您的代码,然后它应该可以工作。然后,您可以尝试查找可能会将上下文更改为活动本身以外的内容的任何东西。
如果您需要更改语言,请使用以下内容:
override fun attachBaseContext(newBase: Context) {
val res = newBase.resources
val config = res.configuration
val languageSetting = instance.getLocale(newBase) //get the locale you want from preferences etc.
if (Build.VERSION.SDK_INT >= 17) {
val locale = if (languageSetting == "")
Locale.getDefault()
else
Locale(languageSetting)
config.setLocale(locale)
if(Build.VERSION.SDK_INT > 24) {
//Using createNewConfigurationContext will cause CompanionDeviceManager to crash
applyOverrideConfiguration(config)
super.attachBaseContext(newBase)
}else {
super.attachBaseContext(newBase.createConfigurationContext(config))
}
} else {
super.attachBaseContext(newBase)
}
}