Android SplashScreen API 从LoginActivity重启MainActivity时图标不显示
问题根因
Android 12及以上系统内置的SplashScreen默认仅在应用冷启动(进程从无到有创建)时才会完整渲染自定义图标和背景,你从LoginActivity调用finishAffinity()后重启MainActivity的操作属于应用热启动范畴,进程没有被销毁,系统会跳过启动图标的绘制流程,仅保留背景色,所以出现图标丢失的问题。
解决方案
方案1:模拟冷启动重建任务栈(推荐)
修改LoginActivity中重启MainActivity的逻辑,通过任务栈标记完全销毁旧任务、创建新任务,触发系统完整的SplashScreen渲染流程:
// LoginActivity 点击事件修改 findViewById<Button>(R.id.button_start_main).setOnClickListener { val restartIntent = Intent(this@LoginActivity, MainActivity::class.java) // 完全清除旧任务栈,创建新的任务栈模拟冷启动 restartIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK startActivity(restartIntent) // 结束当前LoginActivity,不需要调用finishAffinity finish() }
方案2:适配热启动场景手动补全图标
如果业务不允许重建任务栈,可以在MainActivity的SplashScreen展示阶段主动叠加图标View,修改MainActivity代码如下:
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val splashScreen = installSplashScreen() setContentView(R.layout.activity_main) // 针对API31+ 热启动场景手动控制图标展示 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { splashScreen.setOnExitAnimationListener { splashScreenView -> // 保持和原有延迟逻辑对齐,1500ms后关闭启动屏 Handler(Looper.getMainLooper()).postDelayed({ splashScreenView.remove() }, 1500) } } else { // 低版本系统沿用原有逻辑 splashScreen.setKeepVisibleCondition { keepSplashScreen } Handler(Looper.getMainLooper()).postDelayed({ keepSplashScreen = false }, 1500) } findViewById<Button>(R.id.button_login).setOnClickListener { startActivity(Intent(this@MainActivity, LoginActivity::class.java)) } }
内容的提问来源于stack exchange,提问作者Linh
相关产品推荐
相关产品推荐

