App启动优化最佳实践

来源:互联网 发布:2016windows平板推荐 编辑:程序博客网 时间:2024/04/29 16:30

做Android开发,一定写给过启动页,在这里做一些初始化的操作,还有就是显示推广信息。

很普通的一个页面,应用在启动的时候,有时候有白屏/黑屏, 当时能做的就是尽量较少耗时操作。

下面主要总结一下通过主题的方式优化启动页

通过修改主题优化启动时白屏/黑屏


之所以会看到白屏或者黑屏,是和我们的主题有关系的,因为系统默认使用的主题,背景色就是白色/黑色。那么我们自定义一个主题,让默认的样式就是我们想要的,就优化了白屏/黑屏的问题。

首先,我们自定义一个主题,设置一个我们想要的背景

<!-- 启动页主题 --><style name="SplashTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">    <item name="android:windowBackground">@drawable/start_window</item></style>

自定义背景start_window.xml

<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/holo_blue_dark" />    <!-- Your product logo - 144dp color version of your app icon -->    <item>        <bitmap            android:gravity="center"            android:src="@mipmap/ic_launcher" />    </item></layer-list>

最后,在清单文件设置启动页使用我们自定义的主题

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.bitmain.launchtimedemo">    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <!-- 启动页 -->        <activity            android:name=".SplashActivity"            android:theme="@style/SplashTheme">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <!-- 主页 -->        <activity android:name=".MainActivity" />    </application></manifest>

到此大功告成,为了体现出效果,在启动页加载之前,我们模拟一个白屏/黑屏的延时操作

public class SplashActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        // 模拟系统初始化  白屏、黑屏        SystemClock.sleep(1000);        setContentView(R.layout.activity_splash);        // 启动后 停留2秒进入到主页面        new Handler().postDelayed(new Runnable() {            @Override            public void run() {                Intent intent = new Intent(SplashActivity.this, MainActivity.class);                startActivity(intent);                finish();            }        }, 2000);    }} 

1 0
原创粉丝点击