适配Android12启动页

今天我们讲个什么话题呢?我们今天讲的内容是,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:tools="http://schemas.android.com/tools">
    <style name="Theme.MyApplication" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_500</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
    </style>
    <style name="Theme.App.MyStarting" parent="Theme.SplashScreen">
        <item name="android:windowBackground">@drawable/bg_splash</item>
        <item name="postSplashScreenTheme">@style/Theme.MyApplication</item>
    </style>
</resources>

我们要加入一个继承Theme.SplashScreen的主题Theme.App.MyStarting,然后在AndroidManifest.xml指定给MainActivity。然后把原来真正的MainActivity主题,使用postSplashScreenTheme指向原来的主题Theme.MyApplication。

我们可以使用kotlin的协程来请求一些必要的配置数据,然后再在setKeepOnScreenCondition返回false,而非写死的一段时间,这样启动页是否更加优雅了呢?

Android12的系统会自动给所有应用加入一个启动页,就是中央显示一个小logo的那种,我们自己做了适配就不会在Android12上显示两个启动页了。

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dora丶Android

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值