Android Splash

Why

Getting users to the content they care about should be your #1 priority

Android APP 启动,替代白屏、黑屏、闪屏

当我们的 APP 已经启动但尚未在内存中时,用户点击 app 图标启动应用程序与实际调用启动程序 Activity 的 onCreate()之间可能会有一些延迟。在“冷启动”期间,WindowManager 尝试使用应用程序主题中的元素(如 windowBackground)绘制占位符 UI。 因此,我们可以将其更改为显示启动画面的自定义drawable,而不是显示默认的 windowBackground(通常为白色或黑色,也就是我们常说的黑屏、白屏)。这样,启动画面仅在需要时显示,而且不会减慢用户启动 APP 的速度。

How

最佳方式,通过设置 Theme

1、设计一个 splash screen layout(splash.xml)

<?xml version="1.0" encoding="utf-8"?>
<!-- The android:opacity=”opaque” line — this is critical in preventing a flash of black as your theme transitions. -->

<layer-list xmlns:android="http://schemas.android.com/apk/res/android"

  android:opacity="opaque">
  <!-- 背景颜色 -->
  <item android:drawable="@color/white" />

  <item>
    <!-- splash screen 展示的图片 居中 不缩放 -->
    <bitmap
      android:gravity="center"
      android:src="@drawable/headset" />
  </item>
</layer-list>

2、定义一个 theme,使用以上的 drawable 作为 theme 属性 windowBackground 的值

<style name="SplashTheme" parent="AppTheme">
    <item name="android:windowBackground">@drawable/splash</item>
  </style>

3、之后,我们把以上 theme 作为应用主界面 MainActivity 的 theme:

<activity android:name=".MainActivity"
      android:theme="@style/SplashTheme">

      <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>/>
    </activity>

4、最后,我们在 MainActivity 的 onCreate 方法中使用真实的 theme:

public class MainActivity extends BaseActivity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    // Make sure this is before calling super.onCreate
    setTheme(R.style.AppTheme);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
  }
}

Conclusion

使用以上的方式,splash screen 将在 App 初始化过程中展示,而且不用为 splash 创建额外的 activity。Splash screen 的展示时间与 activity 的创建时间相关。

优点:

  1. 不需要单独声明诸如 LaunchActivity/SplashActivity 类的额外的 Activity;
  2. Splash screen 的展示时间与 activity 的创建时间相关。因此不会影响 app 的启动时间;

缺点:

  1. 如果主 Activity 再次被创建,Splash screen 还是会显示(可以用下面的方法解决);
  2. 无法实现按需定制,比如期望该启动画面持续时长等;
  3. 无法加载较大的资源(可以使用懒加载、缓存的方式解决)

注意的问题

1. 只显示一次启动页( App 没被 kill 的情况下)

微信打开之后,按下返回键回到桌面,再打开微信,并不会再看到启动页(除非你手动清了微信的后台或者被系统 kill 了),这个是怎么实现的呢?

其实很简单,只需要重写一下 MainActivity 的 onBackPressed() 方法就行。

// 避免多次启动 启动界面
  @Override
  public void onBackPressed() {
    // super.onBackPressed();
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.addCategory(Intent.CATEGORY_HOME);
    startActivity(intent);
  }

参考文章

带你重新认识:Android Splash页秒开 Activity白屏 Activity黑屏

Splash Screens the Right Way

The (Complete) Android Splash Screen Guide

——乐于分享,共同进步,欢迎留言讨论
——Treat Warnings As Errors
——Any comments greatly appreciated
——Talking is cheap, show me the code

全部评论

相关推荐

韵不凡:软件开发的工作需要博士吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务