想要加快app的启动速度,最重要的就是在app启动时候,对第三方插件进行初始化做一些处理。
对于我开发的多款软件,我总结了,加快app启动分三步。
第一步:在Application中onCreate()进行第三方工具初始化
public void onCreate() { super.onCreate(); ApplicationService.start(this);//这个地方会启动服务做第三方初始化工作 mainThreadInitializeService(); //必须在主线程中初始化的 }
第三方服务,一部分必须在主线程中进行初始化,比如glide,其他的我们可以在后台开启一个IntentService服务进行初始化。
public class ApplicationService extends IntentService { private static final String ACTION_INIT_WHEN_APP_CREATE = "action.INIT"; public ApplicationService() { super("ApplicationService"); //这个地方的构造函数非常坑人,反正要注意下 } public static void start(Application context) { Intent intent = new Intent(context, ApplicationService.class); intent.setAction(ACTION_INIT_WHEN_APP_CREATE); context.startService(intent); } @Override protected void onHandleIntent(@Nullable Intent intent) { if (intent != null) { final String action = intent.getAction(); if (ACTION_INIT_WHEN_APP_CREATE.equals(action)) { performInit(); } } } private void performInit() { } }
写完Service后,我们就要进行注册了
<service android:name=".service.ApplicationService" android:label="第三方初始化服务工作"> <intent-filter> <action android:name="action.INIT" /> </intent-filter> </service>
第二步:对Splash页进行主题设置
我们需要给Splash也设置主题背景
<item name="android:windowBackground">@drawable/bg_splash</item>
这样当我们一启动app的时候,一个线程做初始化工作,另一个做主题,感觉app很快就启动了。
总结:
这部分如果你只是这么写了,速度快了,但是你真的懂其中的原理吗? 这个其实也涉及到Fragment层的一些理论,
App的启动进程,只有懂得原理,才能更好的优化自己的项目。