參考 https://github.com/mmin18/Dex65536 中利用ant打包apk來解決方法數超限android
上述方法中的本質是將能夠分包的jar打包爲一個apk文件,放在assets文件夾下,在應用初始化時加載此apk文件git
下面是具體操做步驟:github
一、將能夠分到第二個包的jar文件利用ant合併合併爲一個jar包,而後轉換爲dex文件,命名爲classes.dex,添加爲壓縮文 件, 並命名爲libs.apkide
二、將libs.apk放入項目的assets文件夾下ui
3.將步驟1中的jar包從項目libs文件夾下刪除,將合併後的jar包依照android.jar的方式引入項目code
項目--右鍵--Build Path --Configure Build Path --- Libraries ---Add External JARsget
四、在項目的Application中添加下面的方法it
public class App extends Application { @Override public void onCreate() { super.onCreate(); dexTool(); } /** * Copy the following code and call dexTool() after super.onCreate() in * Application.onCreate() * <p> * This method hacks the default PathClassLoader and load the secondary dex * file as it's parent. */ @SuppressLint("NewApi") private void dexTool() { File dexDir = new File(getFilesDir(), "dlibs"); dexDir.mkdir(); File dexFile = new File(dexDir, "libs.apk"); File dexOpt = new File(dexDir, "opt"); dexOpt.mkdir(); try { InputStream ins = getAssets().open("libs.apk"); if (dexFile.length() != ins.available()) { FileOutputStream fos = new FileOutputStream(dexFile); byte[] buf = new byte[4096]; int l; while ((l = ins.read(buf)) != -1) { fos.write(buf, 0, l); } fos.close(); } ins.close(); } catch (Exception e) { throw new RuntimeException(e); } ClassLoader cl = getClassLoader(); ApplicationInfo ai = getApplicationInfo(); String nativeLibraryDir = null; if (Build.VERSION.SDK_INT > 8) { nativeLibraryDir = ai.nativeLibraryDir; } else { nativeLibraryDir = "/data/data/" + ai.packageName + "/lib/"; } DexClassLoader dcl = new DexClassLoader(dexFile.getAbsolutePath(), dexOpt.getAbsolutePath(), nativeLibraryDir, cl.getParent()); try { Field f = ClassLoader.class.getDeclaredField("parent"); f.setAccessible(true); f.set(cl, dcl); } catch (Exception e) { throw new RuntimeException(e); } } }
注:Application 中的靜態全局變量會比MutiDex的 instal()方法優先加載,因此建議避免在 Application類中使用引用classes2.dex文件的靜態變量io
到此,問題解決。
class