Android 使用X5核心時,優化載入速度
阿新 • • 發佈:2019-01-30
最近在做Webview載入頁面的時候,用到了騰訊的X5核心,但是在使用過程中發現每次點選連結時,都會有一定的延遲,之後才能跳轉到對應的頁面,這體驗很不好。。。 所以就抽時間找問題,解決問題。
原因
通過一步一步的除錯,發現在載入X5核心的時候,X5核心需要進行一些初始化,這些初始化如果不明確指出執行的執行緒,它就會在你啟動頁面的時候,預設在主執行緒中執行,這就導致了上面的問題出現。
解決問題
提前初始化X5核心
在Application中就對X5核心進行初始化,而且最好另外開闢服務子執行緒進行初始化,防止ANR問題。
最終的解決結果:
1.新增IntentService,初始化X5核心
package com.rencarehealth.mirhythm.service;
import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import com.tencent.smtt.sdk.QbSdk;
public class X5CorePreLoadService extends IntentService {
private static final String TAG = X5CorePreLoadService.class.getSimpleName();
public X5CorePreLoadService() {
super(TAG);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
//在這裡新增我們要執行的程式碼,Intent中可以儲存我們所需的資料,
//每一次通過Intent傳送的命令將被順序執行
initX5();
}
/**
* 初始化X5核心
*/
private void initX5() {
if (!QbSdk.isTbsCoreInited()) {
QbSdk.preInit(getApplicationContext(), null );// 設定X5初始化完成的回撥介面
}
QbSdk.initX5Environment(getApplicationContext(), cb);
}
QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
@Override
public void onViewInitFinished(boolean arg0) {
// TODO Auto-generated method stub
//初始化完成回撥
}
@Override
public void onCoreInitFinished() {
// TODO Auto-generated method stub
}
};
}
2.在application的onCreate中,啟動該服務,進行初始化
/**
* 初始化X5核心
*/
private void preInitX5Core() {
//預載入x5核心
Intent intent = new Intent(this, X5CorePreLoadService.class);
startService(intent);
}
3.最後,別忘了在AndroidManifest.xml中配置服務元件
<service
android:name=".service.X5CorePreLoadService"
android:enabled="true"/>
OK了,再點選Web頁面連結,瞬間跳轉到頁面載入過程!!