对于用户来讲,启动画面是浪费时间的,作为开发者应该尽量避免过长的启动画面,但是安卓应用在启动时很耗时,尤其是冷启动,这个延时是难以避免的,即使只有一个Helloworld应用也有可能出现延时。
究其原因,主要因素是任务在界面绘制前过于集中化。应用启动过程从用户点击launcher图标到看到第一帧这个过程中,主要会经过以下这些过程:
main()->Application:attachBaseContext()->onCreate()-Activity:onCreate()->onStart()->onPostCreate()-onResume()->onPostResume()
要实现一个启动画面,避免黑/白屏出现,主要由Theme着手,有人用设置透明主题的方式解决这一问题,会出现点击图标后停顿一下再打开应用,其实跟黑/白屏并无区别,更改了颜色而已,应用其实已经启动了。
为了实现点击图标立即显示不能用inflate一个layout的方式,创建一个splash.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:drawable="@color/colorPrimary"/>
<item>
<bitmap
android:gravity="center"
android:src="@mipmap/ic_launcher"/>
</item>
</layer-list>
这里设置了背景颜色和一个图片,然后将整个文件设置为SplashTheme的背景:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
</style>
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">@drawable/bg_splash</item>
</style>
</resources>
然后在AndroidManifest.xml中将SplashTheme设置到SplashActivity:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="edu.jnu.splashdemo">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
</activity>
<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>
</application>
</manifest>
最后,在SplashActivity中设置启动跳转:
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
}
onCreate()中不要设置setContentView()。
参考文献:
[1] https://www.bignerdranch.com/blog/splash-screens-the-right-way/
[2] http://blog.youkuaiyun.com/yanzhenjie1003/article/details/52201896