Multidex(二)之Dex預載入優化
阿新 • • 發佈:2019-01-23
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
//只有主程序以及SDK版本5.0以下才走。
if (isMainProcess(Application.this) && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
if (!dexOptDone(base)) {
preLoadDex(base);
}
long startTime = System.currentTimeMillis();
MultiDex.install(this);
LogUtil.i(TAG,"MainProcessCostTime:"+(System.currentTimeMillis() - startTime));
}
}
/**
* 當前版本是否進行過DexOpt操作。
* @param context
* @return
*/
private boolean dexOptDone(Context context) {
SharedPreferences sp = context.getSharedPreferences(
DeviceUtil.getVersionName(context), MODE_MULTI_PROCESS);
return sp.getBoolean("dexoptdone", false);
}
/**
* 在單獨程序中提前進行DexOpt的優化操作;主程序進入等待狀態。
*
* @param base
*/
public void preLoadDex(Context base) {
Intent intent = new Intent(Application.this, PreLoadDexActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
base.startActivity(intent);
while (!dexOptDone(base)) {
try {
//主執行緒開始等待;直到優化程序完成了DexOpt操作。
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}