美文网首页
Android高级进阶之-性能优化-黑白屏问题

Android高级进阶之-性能优化-黑白屏问题

作者: carlwu_186 | 来源:发表于2019-06-27 15:14 被阅读0次

启动优化

优化思路:
APP通过ActivityThread开始,调用Application.onCreate(),再调用到Activity.onCreate(),之后用户才能看见程序界面。所以根本的优化思路就是减少这些onCreate()方法的耗时。

1.黑白屏问题

 <application
        android:theme="@style/AppTheme">

如果这里的theme继承自Theme.AppCompat.Light,

<style name="AppTheme" parent="Theme.AppCompat.Light">

那么APP启动的时候就是白屏,否则就是黑屏。不论是黑屏或白屏,如果没有处理,都是有问题的。

2.优化方案
减少onCreate()方法执行时间,但也不可避免存在间隙黑白屏。所以有两种方案:1.想办法把黑白屏替换成我们自己的过渡屏幕。2.首屏Activity加载完成之前,不显示程序界面,造成系统启动慢,而不是APP启动慢的假象。

方案一实现:
我们跟踪系统默认主题

  <style name="AppTheme" parent="Theme.AppCompat.Light">

向上可以找到

 <style name="Platform.AppCompat.Light" parent="android:Theme.Holo.Light">
        <item name="android:windowBackground">@color/background_material_light</item>
</style>

发现有一个配置是

<item name="android:windowBackground">@color/background_material_light</item>

因此,我们可以在LauncherActivity的主题中,重写android:windowBackground为自己的资源即可。

<style name="SplashActivityTheme" parent="AppTheme">
    <item name="android:windowBackground">@drawable/bg_splash</item>
</style>
      <activity
            android:name=".SplashActivity"
            android:screenOrientation="portrait"
            android:theme="@style/SplashActivityTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

这种方式有一个需要注意的地方,如果设置了android:windowBackground的Activity不被销毁,它指向的资源就会一直占用内存,甚至导致后期的过度绘制,所以这种情况下,我们还需要在该Activity的setContentView()之前设置windowBackground为空或透明:

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.getWindow().getDecorView().setBackground(new ColorDrawable(Color.TRANSPARENT));
        setContentView(R.layout.activity_splash);
    }

方案二实现:
同上,我们发现theme还有一个配置:

<item name="android:windowDisablePreview">false</item>

如果把它设置为true,就可以取消Activity的预览。我们只给首页Activity指定这个配置即可。

<style name="SplashActivityTheme" parent="AppTheme">
    <item name="android:windowBackground">@null</item>
    <item name="android:windowDisablePreview">true</item>
</style>
      <activity
            android:name=".SplashActivity"
            android:screenOrientation="portrait"
            android:theme="@style/SplashActivityTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

相关文章

网友评论

      本文标题:Android高级进阶之-性能优化-黑白屏问题

      本文链接:https://www.haomeiwen.com/subject/dqdrcctx.html