凡科建站帮忙做网站,深圳市水榭花都房地产公司,珠海网站开发定制,合肥企业网站建设今天我们讲个什么话题呢#xff1f;我们今天讲的内容是#xff0c;Android12新启动页的支持API。
启动页我想大家都不陌生吧#xff0c;通常的写法就是先创建一个SplashActivity#xff0c;在onCreate中
Handler(Looper.getMainLooper()).postDelayed({// 在这里跳转主界…今天我们讲个什么话题呢我们今天讲的内容是Android12新启动页的支持API。
启动页我想大家都不陌生吧通常的写法就是先创建一个SplashActivity在onCreate中
Handler(Looper.getMainLooper()).postDelayed({// 在这里跳转主界面
}, 2000)对吧
Android开发本不使用启动页结果就被我们一些大厂玩坏了比较有名的就是腾讯QQ的那只企鹅估计是为了体现品牌形象或是为了方便打广告于是就强加了一个启动页。这样一来倒好各个互联网平台纷纷效仿人家技术好倒罢了一些新入行的小白也开始这样写于是就引出了启动黑屏或白屏一段时间等问题这里我就不多吐槽了。
奇怪的是Android官方现在还真搞了这么一个启动页的API目的应该不是为了方便打广告而是保证最快打开一个页面展示给用户然后耗时的延后加载。不要让用户觉得卡顿从而引发不好的用户体验。
言归正题怎么使用呢在此之前我们要知道冷启动、温启动和热启动。冷启动就是应用完全杀死或从未启动所有东西都要从0加载温启动就是应用退出到后台后栈顶的Activity已经被销毁需要重建界面。而热启动就是退出后台没多久可以继续使用的时候。
我们要引入这么一个包
implementation androidx.core:core-splashscreen:1.0.0-beta02然后在MainActivity中加入
class MainActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) {val splashScreen installSplashScreen()super.onCreate(savedInstanceState)splashScreen.setKeepOnScreenCondition {SystemClock.sleep(2000)false}setContentView(R.layout.activity_main)}
}installSplashScreen()最好在onCreate之前。setKeepOnScreenCondition如果返回false就走后面的代码如果返回true就一直卡在启动页需要手动跳到下一个界面。所以我们可以在返回false之前做一些初始化和加载操作。这样写了确实使用了SplashScreen啊但是不好看啊于是我们要改一下闪屏的样式。在themes.xml中
resources xmlns:toolshttp://schemas.android.com/toolsstyle nameTheme.MyApplication parentTheme.MaterialComponents.DayNight.DarkActionBar!-- Primary brand color. --item namecolorPrimarycolor/purple_500/itemitem namecolorPrimaryVariantcolor/purple_700/itemitem namecolorOnPrimarycolor/white/item!-- Secondary brand color. --item namecolorSecondarycolor/teal_200/itemitem namecolorSecondaryVariantcolor/teal_700/itemitem namecolorOnSecondarycolor/black/item!-- Status bar color. --item nameandroid:statusBarColor tools:targetApil?attr/colorPrimaryVariant/item/stylestyle nameTheme.App.MyStarting parentTheme.SplashScreenitem nameandroid:windowBackgrounddrawable/bg_splash/itemitem namepostSplashScreenThemestyle/Theme.MyApplication/item/style
/resources我们要加入一个继承Theme.SplashScreen的主题Theme.App.MyStarting然后在AndroidManifest.xml指定给MainActivity。然后把原来真正的MainActivity主题使用postSplashScreenTheme指向原来的主题Theme.MyApplication。
我们可以使用kotlin的协程来请求一些必要的配置数据然后再在setKeepOnScreenCondition返回false而非写死的一段时间这样启动页是否更加优雅了呢
Android12的系统会自动给所有应用加入一个启动页就是中央显示一个小logo的那种我们自己做了适配就不会在Android12上显示两个启动页了。