我在Handler(Looper.getMainLooper())中体验了有趣的行为。如果我的应用程序主题(白天/夜晚)设置为与OS设置不同,它将被执行两次。例如,如果在设备设置中关闭了黑暗模式,并且我的应用程序MainActivity应用了黑暗主题,那么MainActivity会启动两次。我没有找到任何解释为什么会发生这种事。
SplashActivity非常简单的
class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.splash_screen_layout)
Handler(Looper.getMainLooper()).postDelayed({
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
Log.i("SPLASH","Main activity started")
finish()
}, 2000)
}
}Main活动具有以下功能,用于检查应用程序设置中保存的主题并加以应用:
函数
private fun checkDarkMode(){
when (MainSettings(this).darkMode) {
0 -> {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
delegate.applyDayNight()
}
1 -> {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
delegate.applyDayNight()
}
2 -> {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
delegate.applyDayNight()
}
}
}因此,如果在设备设置中关闭黑暗模式,那么AppCompatDelegate.MODE_NIGHT_YES将执行两次处理程序代码,而其他处理程序代码只执行一次。
反之亦然,如果设备处于黑暗状态,则对AppCompatDelegate.MODE_NIGHT_NO执行两次代码。
正如我所说的,我没有找到任何解释或解决方案,所以我所做的只是将处理程序定义为val,并在onPause或onDestroy of SplashActivity中取消了它的所有内容。
private val handler = Handler(Looper.getMainLooper())
override fun onPause() {
super.onPause()
handler.removeCallbacksAndMessages(null)
}所以我的问题是,为什么会发生这种情况,还有什么办法可以避免这种情况发生呢?
发布于 2021-01-25 15:27:00
我想看一下AppCompatDelegate的源代码,它是这里 (关于它重新创建活动的部分,请看第201行的内容)。
我无法为您的问题提供直接解决方案,但另一种选择是继承DayNight主题之一(尽管您确实失去了在Android 10以下设置夜间主题的能力,但在我看来,这会使事情变得简单得多)。
编辑:您可能能够在一个checkDarkMode类中执行您的Application方法,这应该能够在创建任何活动之前设置正确的模式(从而避免在其更改时再次创建它们)。
public class MyApplication extends Application {
public void onCreate() {
super.onCreate();
checkDarkMode()
}https://stackoverflow.com/questions/65887412
复制相似问题