从Theme方向来优化加载时间

122 阅读1分钟

注意:这种做法可以达到"秒开"APP的效果,只是一种假象,不是真正提升App启动的速度。

在主题上使用windowBackground属性为SplashActivity提供一个简单的自定义Drawable

先创建一个drawable

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" android:opacity="opaque">
  <!-- The background color, preferably the same as your normal theme -->
  <item android:drawable="@android:color/white"/>
  <!-- Your product logo - 144dp color version of your app icon -->
  <item>
    <bitmap
      android:src="@drawable/product_logo_144dp"
      android:gravity="center"/>
  </item>
</layer-list>

随后运用到style上

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

最后配置在AndroidManifest上

<activity
    android:name=".ui.activity.signin.SplashActivity"
    android:configChanges="orientation|keyboard|keyboardHidden|screenSize"
    android:screenOrientation="portrait"
    android:theme="@style/SplashTheme">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

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

如果你想过渡到App本身的主题,只需要在super.onCreate()方法和setContentVIew()方法之前调用setTheme(R.style.AppTheme)即可

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

这里简单介绍下其中陌生的属性:

android:opacity=”opaque”是为了防止在启动的时候出现背景的闪烁