DEX分包引起的apk首次啟動(dòng)時(shí)間過(guò)長(zhǎng)問(wèn)題

在android apk中如果項(xiàng)目引用的方法數(shù)超過(guò)64k(包括android框架方法、庫(kù)方法局齿、自己代碼中的方法)的限制剧劝,就需要對(duì)apk進(jìn)行dex分包處理。當(dāng)?shù)谝淮螁?dòng)app的時(shí)候抓歼,系統(tǒng)會(huì)執(zhí)行復(fù)雜的計(jì)算來(lái)確定主dex文件所需要的類讥此,往往這里會(huì)花費(fèi)很多時(shí)間。解決的方案就是通過(guò)mutildex.keep文件來(lái)告訴主dex文件所需要包含的類谣妻。這樣app首次啟動(dòng)的時(shí)候暂论,就不需要進(jìn)行復(fù)雜的計(jì)算來(lái)確定主dex文件所需要包含的類了。需要做的步驟如下:

1. 在build.gradle同目錄中新建multidex.keep文件

2. 在build.gradle文件中指明主dex文件該包含的class文件應(yīng)該從multidex.keep文件獲取

android.applicationVariants.all { variant ->

? ? ? ? task "fix${variant.name.capitalize()}MainDexClassList" << {

? ? ? ? ? ? logger.info "Fixing main dex keep file for $variant.name"

? ? ? ? ? ? File keepFile = new File("$buildDir/intermediates/multi-dex/$variant.buildType.name/maindexlist.txt")

? ? ? ? ? ? keepFile.withWriterAppend { w ->

? ? ? ? ? ? ? ? // Get a reader for the input file

? ? ? ? ? ? ? ? w.append('\n')

? ? ? ? ? ? ? ? new File("${projectDir}/multidex.keep").withReader { r ->

? ? ? ? ? ? ? ? ? ? // And write data from the input into the output

? ? ? ? ? ? ? ? ? ? w << r << '\n'

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? logger.info "Updated main dex keep file for ${keepFile.getAbsolutePath()}\n$keepFile.text"

? ? ? ? ? ? }

? ? ? ? }

? ? }

? ? tasks.whenTaskAdded { task ->

? ? ? ? android.applicationVariants.all { variant ->

? ? ? ? ? ? if (task.name == "create${variant.name.capitalize()}MainDexClassList") {

? ? ? ? ? ? ? ? task.finalizedBy "fix${variant.name.capitalize()}MainDexClassList"

? ? ? ? ? ? }

? ? ? ? }

? ? }


3.在multidex.keep文件中添加主dex文件所需的class文件拌禾。主dex文件所需的class文件可以通過(guò)以下方法獲取取胎。調(diào)用MultiDexUtils的getLoadedExternalDexClasses方法即可獲取所需的class文件的list。


import android.content.Context;

import android.content.SharedPreferences;

import android.content.pm.ApplicationInfo;

import android.content.pm.PackageManager;

import android.os.Build;

import java.io.File;

import java.io.IOException;

import java.util.ArrayList;

import java.util.Enumeration;

import java.util.List;

import dalvik.system.DexFile;

public class MultiDexUtils {

? ? private static final String EXTRACTED_NAME_EXT = ".classes";

? ? private static final String EXTRACTED_SUFFIX = ".zip";

? ? private static final String SECONDARY_FOLDER_NAME = "code_cache" + File.separator +

? ? ? ? ? ? "secondary-dexes";

? ? private static final String PREFS_FILE = "multidex.version";

? ? private static final String KEY_DEX_NUMBER = "dex.number";

? ? private SharedPreferences getMultiDexPreferences(Context context) {

? ? ? ? return context.getSharedPreferences(PREFS_FILE,

? ? ? ? ? ? ? ? Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB

? ? ? ? ? ? ? ? ? ? ? ? ? Context.MODE_PRIVATE

? ? ? ? ? ? ? ? ? ? ? ? : Context.MODE_PRIVATE | Context.MODE_MULTI_PROCESS);

? ? }

? ? /**

? ? * get all the dex path

? ? *

? ? * @param context the application context

? ? * @return all the dex path

? ? * @throws PackageManager.NameNotFoundException

? ? * @throws IOException

? ? */

? ? public List<String> getSourcePaths(Context context) throws PackageManager.NameNotFoundException, IOException {

? ? ? ? final ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);

? ? ? ? final File sourceApk = new File(applicationInfo.sourceDir);

? ? ? ? final File dexDir = new File(applicationInfo.dataDir, SECONDARY_FOLDER_NAME);

? ? ? ? final List<String> sourcePaths = new ArrayList<>();

? ? ? ? sourcePaths.add(applicationInfo.sourceDir); //add the default apk path

? ? ? ? //the prefix of extracted file, ie: test.classes

? ? ? ? final String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT;

? ? ? ? //the total dex numbers

? ? ? ? final int totalDexNumber = getMultiDexPreferences(context).getInt(KEY_DEX_NUMBER, 1);

? ? ? ? for (int secondaryNumber = 2; secondaryNumber <= totalDexNumber; secondaryNumber++) {

? ? ? ? ? ? //for each dex file, ie: test.classes2.zip, test.classes3.zip...

? ? ? ? ? ? final String fileName = extractedFilePrefix + secondaryNumber + EXTRACTED_SUFFIX;

? ? ? ? ? ? final File extractedFile = new File(dexDir, fileName);

? ? ? ? ? ? if (extractedFile.isFile()) {

? ? ? ? ? ? ? ? sourcePaths.add(extractedFile.getAbsolutePath());

? ? ? ? ? ? ? ? //we ignore the verify zip part

? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? throw new IOException("Missing extracted secondary dex file '" +

? ? ? ? ? ? ? ? ? ? ? ? extractedFile.getPath() + "'");

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return sourcePaths;

? ? }

? ? /**

? ? * get all the external classes name in "classes2.dex", "classes3.dex" ....

? ? *

? ? * @param context the application context

? ? * @return all the classes name in the external dex

? ? * @throws PackageManager.NameNotFoundException

? ? * @throws IOException

? ? */

? ? public List<String> getExternalDexClasses(Context context) throws PackageManager.NameNotFoundException, IOException {

? ? ? ? final List<String> paths = getSourcePaths(context);

? ? ? ? if(paths.size() <= 1) {

? ? ? ? ? ? // no external dex

? ? ? ? ? ? return null;

? ? ? ? }

? ? ? ? // the first element is the main dex, remove it.

? ? ? ? paths.remove(0);

? ? ? ? final List<String> classNames = new ArrayList<>();

? ? ? ? for (String path : paths) {

? ? ? ? ? ? try {

? ? ? ? ? ? ? ? DexFile dexfile = null;

? ? ? ? ? ? ? ? if (path.endsWith(EXTRACTED_SUFFIX)) {

? ? ? ? ? ? ? ? ? ? //NOT use new DexFile(path), because it will throw "permission error in /data/dalvik-cache"

? ? ? ? ? ? ? ? ? ? dexfile = DexFile.loadDex(path, path + ".tmp", 0);

? ? ? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? ? ? dexfile = new DexFile(path);

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? final Enumeration<String> dexEntries = dexfile.entries();

? ? ? ? ? ? ? ? while (dexEntries.hasMoreElements()) {

? ? ? ? ? ? ? ? ? ? classNames.add(dexEntries.nextElement());

? ? ? ? ? ? ? ? }

? ? ? ? ? ? } catch (IOException e) {

? ? ? ? ? ? ? ? throw new IOException("Error at loading dex file '" +

? ? ? ? ? ? ? ? ? ? ? ? path + "'");

? ? ? ? ? ? }

? ? ? ? }

? ? ? ? return classNames;

? ? }

? ? /**

? ? * Get all loaded external classes name in "classes2.dex", "classes3.dex" ....

? ? * @param context

? ? * @return get all loaded external classes

? ? */

? ? public List<String> getLoadedExternalDexClasses(Context context) {

? ? ? ? try {

? ? ? ? ? ? final List<String> externalDexClasses = getExternalDexClasses(context);

? ? ? ? ? ? if (externalDexClasses != null && !externalDexClasses.isEmpty()) {

? ? ? ? ? ? ? ? final ArrayList<String> classList = new ArrayList<>();

? ? ? ? ? ? ? ? final java.lang.reflect.Method m = ClassLoader.class.getDeclaredMethod("findLoadedClass", new Class[]{String.class});

? ? ? ? ? ? ? ? m.setAccessible(true);

? ? ? ? ? ? ? ? final ClassLoader cl = context.getClassLoader();

? ? ? ? ? ? ? ? for (String clazz : externalDexClasses) {

? ? ? ? ? ? ? ? ? ? if (m.invoke(cl, clazz) != null) {

? ? ? ? ? ? ? ? ? ? ? ? classList.add(clazz.replaceAll("\\.", "/").replaceAll("$", ".class"));

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? return classList;

? ? ? ? ? ? }

? ? ? ? } catch (Exception e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? }

? ? ? ? return null;

? ? }

}


4.再把list數(shù)組寫(xiě)到手機(jī)sd卡的txt文件中湃窍,把txt文件的內(nèi)容復(fù)制到multidex.keep即可闻蛀。


MultiDexUtils dexUtils = new MultiDexUtils();

? ? ? ? List<String> des = dexUtils.getLoadedExternalDexClasses(this);

? ? ? ? String sdCardDir = Environment.getExternalStorageDirectory().getAbsolutePath();

? ? ? ? File saveFile = new File(sdCardDir, "aaaa.txt");

? ? ? ? try {

? ? ? ? ? ? FileOutputStream outStream = new FileOutputStream(saveFile);

? ? ? ? ? ? outStream.write(listToString(des).getBytes());

? ? ? ? ? ? outStream.close();

? ? ? ? } catch (IOException e) {

? ? ? ? ? ? e.printStackTrace();

? ? ? ? }


public static String listToString(List<String> stringList){

? ? ? ? if(stringList==null) {

? ? ? ? ? ? return null;

? ? ? ? }

? ? ? ? StringBuilder result = new StringBuilder();

? ? ? ? boolean flag=false;

? ? ? ? for(String string : stringList) {

? ? ? ? ? ? if(flag) {

? ? ? ? ? ? ? ? result.append("\n");

? ? ? ? ? ? }else{

? ? ? ? ? ? ? ? flag=true;

? ? ? ? ? ? }

? ? ? ? ? ? result.append(string);

? ? ? ? }

? ? ? ? return result.toString();

? ? }


經(jīng)過(guò)我公司的app測(cè)試,可優(yōu)化app首次啟動(dòng)從4秒左右減到1秒左右您市。優(yōu)化還是挺明顯的觉痛。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市茵休,隨后出現(xiàn)的幾起案子薪棒,更是在濱河造成了極大的恐慌,老刑警劉巖榕莺,帶你破解...
    沈念sama閱讀 222,000評(píng)論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件俐芯,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡钉鸯,警方通過(guò)查閱死者的電腦和手機(jī)吧史,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,745評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)唠雕,“玉大人贸营,你說(shuō)我怎么就攤上這事吨述。” “怎么了钞脂?”我有些...
    開(kāi)封第一講書(shū)人閱讀 168,561評(píng)論 0 360
  • 文/不壞的土叔 我叫張陵揣云,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我冰啃,道長(zhǎng)灵再,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 59,782評(píng)論 1 298
  • 正文 為了忘掉前任亿笤,我火速辦了婚禮翎迁,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘净薛。我一直安慰自己汪榔,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,798評(píng)論 6 397
  • 文/花漫 我一把揭開(kāi)白布肃拜。 她就那樣靜靜地躺著痴腌,像睡著了一般。 火紅的嫁衣襯著肌膚如雪燃领。 梳的紋絲不亂的頭發(fā)上士聪,一...
    開(kāi)封第一講書(shū)人閱讀 52,394評(píng)論 1 310
  • 那天,我揣著相機(jī)與錄音猛蔽,去河邊找鬼剥悟。 笑死,一個(gè)胖子當(dāng)著我的面吹牛曼库,可吹牛的內(nèi)容都是我干的区岗。 我是一名探鬼主播,決...
    沈念sama閱讀 40,952評(píng)論 3 421
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼毁枯,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼慈缔!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起种玛,我...
    開(kāi)封第一講書(shū)人閱讀 39,852評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤藐鹤,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后赂韵,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體娱节,經(jīng)...
    沈念sama閱讀 46,409評(píng)論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,483評(píng)論 3 341
  • 正文 我和宋清朗相戀三年右锨,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了括堤。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,615評(píng)論 1 352
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡绍移,死狀恐怖悄窃,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情蹂窖,我是刑警寧澤轧抗,帶...
    沈念sama閱讀 36,303評(píng)論 5 350
  • 正文 年R本政府宣布,位于F島的核電站瞬测,受9級(jí)特大地震影響横媚,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜月趟,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,979評(píng)論 3 334
  • 文/蒙蒙 一灯蝴、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧孝宗,春花似錦穷躁、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,470評(píng)論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至婚被,卻和暖如春狡忙,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背址芯。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,571評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工灾茁, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人谷炸。 一個(gè)月前我還...
    沈念sama閱讀 49,041評(píng)論 3 377
  • 正文 我出身青樓删顶,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親淑廊。 傳聞我的和親對(duì)象是個(gè)殘疾皇子逗余,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,630評(píng)論 2 359