(转)解决android eclipse方法超出65535的问题


转载from : http://blog.csdn.net/qq_19764133/article/details/54020508


开发了一个项目,不断加功能,终于遇到了个问题,就是方法数量超过65536个了。这就尴尬了,这个功能有必须要,其他的该删的都删了。从网上找了很多方法,试了感觉不完整,不知道是个人理解不够还是别的原因,反正这次记录一下,以便下次需要,又忘记了。

1、首先得装好ant,这个ant配置安装网上一大把,就过了;

2、然后弄个xml文件,格式如下:

<?xml version="1.0" encoding="utf-8"?>  
<project name="libs" basedir="D:\all" default="makeSuperJar">  
<target name="makeSuperJar"  description="description">  
    <jar destfile="libs.jar">  
    <zipfileset src="alipaySdk-20160803.jar"/>   
        <zipfileset src="BaiduLBS_Android.jar"/>          
        <zipfileset src="gson-2.2.2.jar"/>
        <zipfileset src="httpmime-4.1.2.jar"/>
        <zipfileset src="javacv.jar"/>
        <zipfileset src="javacpp.jar"/>
        <zipfileset src="jg_filter_sdk_1.1.jar"/>
<zipfileset src="libammsdk.jar"/>
        <zipfileset src="MobCommons-2016.1107.1809.jar"/>
        <zipfileset src="MobTools-2016.1107.1809.jar"/>
        <zipfileset src="Msc.jar"/>
        <zipfileset src="ormlite-android-4.48.jar"/>
        <zipfileset src="ormlite-core-4.48.jar"/>
        <zipfileset src="ormlite-jdbc-4.48.jar"/>
        <zipfileset src="ShareSDK-Core-2.7.10.jar"/>
        <zipfileset src="ShareSDK-QQ-2.7.10.jar"/>
        <zipfileset src="ShareSDK-QZone-2.7.10.jar"/>
        <zipfileset src="ShareSDK-ShortMessage-2.7.10.jar"/>
        <zipfileset src="ShareSDK-SinaWeibo-2.7.10.jar"/>
        <zipfileset src="ShareSDK-Wechat-2.7.10.jar"/>
        <zipfileset src="ShareSDK-Wechat-Core-2.7.10.jar"/>
        <zipfileset src="ShareSDK-Wechat-Moments-2.7.10.jar"/>
        <zipfileset src="Xg_sdk_v2.43_20160308_1031.jar"/>
        <zipfileset src="zxing.jar"/>
    </jar>  
</target>  
</project>

这里你只需要改下你的basedir目录地址,destfile输出文件的名字和zipfileset你需要合并的jar即可。这里一定要注意上面的配置文件和要合并的包在同一个目录下,不然会报无法找到project all的错

3、准备条件做好了以后,打开dos,输入ant -buildfile D:libs\b.xml 这时如果成功了就会D盘all目录下就会出现libs.jar包

4、将打好jar包 项目--右键--Build Path --Configure Build Path --- Libraries ---AddExternal JARs导入,删除以前libs下面的包,前提是这些包都在2中xml里有,

5、生成dex文件,先用dos进入到sdk\build-tools\21.0.0目录下,后面的21.0.0是可以不同的,然后输入dx --dex --output=D:\classes.dex D:\all\libs.jar ,这里libs.jar 是3生成的jar包,成功了就会生成classes.dex文件在D盘根目录下,将文件重命名为classes2.dex直接复制到项目src目录即可。

6、OK,这里到执行还差重要的一步了就是导入MutiDex类库,这个网上一大把,这个文章中有这个类库代码,也是我参照的文章http://www.mamicode.com/info-detail-1578920.html。我这里就多此一举了:

MultiDex类

[java]  view plain  copy
  1. import java.io.File;  
  2. import java.io.IOException;  
  3. import java.lang.reflect.Array;  
  4. import java.lang.reflect.Field;  
  5. import java.lang.reflect.InvocationTargetException;  
  6. import java.lang.reflect.Method;  
  7. import java.util.ArrayList;  
  8. import java.util.Arrays;  
  9. import java.util.HashSet;  
  10. import java.util.List;  
  11. import java.util.ListIterator;  
  12. import java.util.Set;  
  13. import java.util.regex.Matcher;  
  14. import java.util.regex.Pattern;  
  15. import java.util.zip.ZipFile;  
  16.   
  17. import android.app.Application;  
  18. import android.content.Context;  
  19. import android.content.pm.ApplicationInfo;  
  20. import android.content.pm.PackageManager;  
  21. import android.content.pm.PackageManager.NameNotFoundException;  
  22. import android.os.Build;  
  23. import android.util.Log;  
  24. import dalvik.system.DexFile;  
  25.   
  26. /** 
  27.  * Monkey patches {@link Context#getClassLoader() the application context class 
  28.  * loader} in order to load classes from more than one dex file. The primary 
  29.  * {@code classes.dex} must contain the classes necessary for calling this 
  30.  * class methods. Secondary dex files named classes2.dex, classes3.dex... found 
  31.  * in the application apk will be added to the classloader after first call to 
  32.  * {@link #install(Context)}. 
  33.  * 
  34.  * <p/> 
  35.  * This library provides compatibility for platforms with API level 4 through 20. This library does 
  36.  * nothing on newer versions of the platform which provide built-in support for secondary dex files. 
  37.  */  
  38. public final class MultiDex {  
  39.   
  40.     static final String TAG = "MultiDex";  
  41.   
  42.     private static final String OLD_SECONDARY_FOLDER_NAME = "secondary-dexes";  
  43.   
  44.     private static final String SECONDARY_FOLDER_NAME = "code_cache" + File.separator +  
  45.         "secondary-dexes";  
  46.   
  47.     private static final int MAX_SUPPORTED_SDK_VERSION = 20;  
  48.   
  49.     private static final int MIN_SDK_VERSION = 4;  
  50.   
  51.     private static final int VM_WITH_MULTIDEX_VERSION_MAJOR = 2;  
  52.   
  53.     private static final int VM_WITH_MULTIDEX_VERSION_MINOR = 1;  
  54.   
  55.     private static final Set<String> installedApk = new HashSet<String>();  
  56.   
  57.     private static final boolean IS_VM_MULTIDEX_CAPABLE =  
  58.             isVMMultidexCapable(System.getProperty("java.vm.version"));  
  59.   
  60.     private MultiDex() {}  
  61.   
  62.     /** 
  63.      * Patches the application context class loader by appending extra dex files 
  64.      * loaded from the application apk. This method should be called in the 
  65.      * attachBaseContext of your {@link Application}, see 
  66.      * {@link MultiDexApplication} for more explanation and an example. 
  67.      * 
  68.      * @param context application context. 
  69.      * @throws RuntimeException if an error occurred preventing the classloader 
  70.      *         extension. 
  71.      */  
  72.     public static void install(Context context) {  
  73.         Log.i(TAG, "install");  
  74.         if (IS_VM_MULTIDEX_CAPABLE) {  
  75.             Log.i(TAG, "VM has multidex support, MultiDex support library is disabled.");  
  76.             return;  
  77.         }  
  78.   
  79.         if (Build.VERSION.SDK_INT < MIN_SDK_VERSION) {  
  80.             throw new RuntimeException("Multi dex installation failed. SDK " + Build.VERSION.SDK_INT  
  81.                     + " is unsupported. Min SDK version is " + MIN_SDK_VERSION + ".");  
  82.         }  
  83.   
  84.         try {  
  85.             ApplicationInfo applicationInfo = getApplicationInfo(context);  
  86.             if (applicationInfo == null) {  
  87.                 // Looks like running on a test Context, so just return without patching.  
  88.                 return;  
  89.             }  
  90.   
  91.             synchronized (installedApk) {  
  92.                 String apkPath = applicationInfo.sourceDir;  
  93.                 if (installedApk.contains(apkPath)) {  
  94.                     return;  
  95.                 }  
  96.                 installedApk.add(apkPath);  
  97.   
  98.                 if (Build.VERSION.SDK_INT > MAX_SUPPORTED_SDK_VERSION) {  
  99.                     Log.w(TAG, "MultiDex is not guaranteed to work in SDK version "  
  100.                             + Build.VERSION.SDK_INT + ": SDK version higher than "  
  101.                             + MAX_SUPPORTED_SDK_VERSION + " should be backed by "  
  102.                             + "runtime with built-in multidex capabilty but it‘s not the "  
  103.                             + "case here: java.vm.version=\""  
  104.                             + System.getProperty("java.vm.version") + "\"");  
  105.                 }  
  106.   
  107.                 /* The patched class loader is expected to be a descendant of 
  108.                  * dalvik.system.BaseDexClassLoader. We modify its 
  109.                  * dalvik.system.DexPathList pathList field to append additional DEX 
  110.                  * file entries. 
  111.                  */  
  112.                 ClassLoader loader;  
  113.                 try {  
  114.                     loader = context.getClassLoader();  
  115.                 } catch (RuntimeException e) {  
  116.                     /* Ignore those exceptions so that we don‘t break tests relying on Context like 
  117.                      * a android.test.mock.MockContext or a android.content.ContextWrapper with a 
  118.                      * null base Context. 
  119.                      */  
  120.                     Log.w(TAG, "Failure while trying to obtain Context class loader. " +  
  121.                             "Must be running in test mode. Skip patching.", e);  
  122.                     return;  
  123.                 }  
  124.                 if (loader == null) {  
  125.                     // Note, the context class loader is null when running Robolectric tests.  
  126.                     Log.e(TAG,  
  127.                             "Context class loader is null. Must be running in test mode. "  
  128.                             + "Skip patching.");  
  129.                     return;  
  130.                 }  
  131.   
  132.                 try {  
  133.                   clearOldDexDir(context);  
  134.                 } catch (Throwable t) {  
  135.                   Log.w(TAG, "Something went wrong when trying to clear old MultiDex extraction, "  
  136.                       + "continuing without cleaning.", t);  
  137.                 }  
  138.   
  139.                 File dexDir = new File(applicationInfo.dataDir, SECONDARY_FOLDER_NAME);  
  140.                 List<File> files = MultiDexExtractor.load(context, applicationInfo, dexDir, false);  
  141.                 if (checkValidZipFiles(files)) {  
  142.                     installSecondaryDexes(loader, dexDir, files);  
  143.                 } else {  
  144.                     Log.w(TAG, "Files were not valid zip files.  Forcing a reload.");  
  145.                     // Try again, but this time force a reload of the zip file.  
  146.                     files = MultiDexExtractor.load(context, applicationInfo, dexDir, true);  
  147.   
  148.                     if (checkValidZipFiles(files)) {  
  149.                         installSecondaryDexes(loader, dexDir, files);  
  150.                     } else {  
  151.                         // Second time didn‘t work, give up  
  152.                         throw new RuntimeException("Zip files were not valid.");  
  153.                     }  
  154.                 }  
  155.             }  
  156.   
  157.         } catch (Exception e) {  
  158.             Log.e(TAG, "Multidex installation failure", e);  
  159.             throw new RuntimeException("Multi dex installation failed (" + e.getMessage() + ").");  
  160.         }  
  161.         Log.i(TAG, "install done");  
  162.     }  
  163.   
  164.     private static ApplicationInfo getApplicationInfo(Context context)  
  165.             throws NameNotFoundException {  
  166.         PackageManager pm;  
  167.         String packageName;  
  168.         try {  
  169.             pm = context.getPackageManager();  
  170.             packageName = context.getPackageName();  
  171.         } catch (RuntimeException e) {  
  172.             /* Ignore those exceptions so that we don‘t break tests relying on Context like 
  173.              * a android.test.mock.MockContext or a android.content.ContextWrapper with a null 
  174.              * base Context. 
  175.              */  
  176.             Log.w(TAG, "Failure while trying to obtain ApplicationInfo from Context. " +  
  177.                     "Must be running in test mode. Skip patching.", e);  
  178.             return null;  
  179.         }  
  180.         if (pm == null || packageName == null) {  
  181.             // This is most likely a mock context, so just return without patching.  
  182.             return null;  
  183.         }  
  184.         ApplicationInfo applicationInfo =  
  185.                 pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);  
  186.         return applicationInfo;  
  187.     }  
  188.   
  189.     /** 
  190.      * Identifies if the current VM has a native support for multidex, meaning there is no need for 
  191.      * additional installation by this library. 
  192.      * @return true if the VM handles multidex 
  193.      */  
  194.     /* package visible for test */  
  195.     static boolean isVMMultidexCapable(String versionString) {  
  196.         boolean isMultidexCapable = false;  
  197.         if (versionString != null) {  
  198.             Matcher matcher = Pattern.compile("(\\d+)\\.(\\d+)(\\.\\d+)?").matcher(versionString);  
  199.             if (matcher.matches()) {  
  200.                 try {  
  201.                     int major = Integer.parseInt(matcher.group(1));  
  202.                     int minor = Integer.parseInt(matcher.group(2));  
  203.                     isMultidexCapable = (major > VM_WITH_MULTIDEX_VERSION_MAJOR)  
  204.                             || ((major == VM_WITH_MULTIDEX_VERSION_MAJOR)  
  205.                                     && (minor >= VM_WITH_MULTIDEX_VERSION_MINOR));  
  206.                 } catch (NumberFormatException e) {  
  207.                     // let isMultidexCapable be false  
  208.                 }  
  209.             }  
  210.         }  
  211.         Log.i(TAG, "VM with version " + versionString +  
  212.                 (isMultidexCapable ?  
  213.                         " has multidex support" :  
  214.                         " does not have multidex support"));  
  215.         return isMultidexCapable;  
  216.     }  
  217.   
  218.     private static void installSecondaryDexes(ClassLoader loader, File dexDir, List<File> files)  
  219.             throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException,  
  220.             InvocationTargetException, NoSuchMethodException, IOException {  
  221.         if (!files.isEmpty()) {  
  222.             if (Build.VERSION.SDK_INT >= 19) {  
  223.                 V19.install(loader, files, dexDir);  
  224.             } else if (Build.VERSION.SDK_INT >= 14) {  
  225.                 V14.install(loader, files, dexDir);  
  226.             } else {  
  227.                 V4.install(loader, files);  
  228.             }  
  229.         }  
  230.     }  
  231.   
  232.     /** 
  233.      * Returns whether all files in the list are valid zip files.  If {@code files} is empty, then 
  234.      * returns true. 
  235.      */  
  236.     private static boolean checkValidZipFiles(List<File> files) {  
  237.         for (File file : files) {  
  238.             if (!MultiDexExtractor.verifyZipFile(file)) {  
  239.                 return false;  
  240.             }  
  241.         }  
  242.         return true;  
  243.     }  
  244.   
  245.     /** 
  246.      * Locates a given field anywhere in the class inheritance hierarchy. 
  247.      * 
  248.      * @param instance an object to search the field into. 
  249.      * @param name field name 
  250.      * @return a field object 
  251.      * @throws NoSuchFieldException if the field cannot be located 
  252.      */  
  253.     private static Field findField(Object instance, String name) throws NoSuchFieldException {  
  254.         for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {  
  255.             try {  
  256.                 Field field = clazz.getDeclaredField(name);  
  257.   
  258.   
  259.                 if (!field.isAccessible()) {  
  260.                     field.setAccessible(true);  
  261.                 }  
  262.   
  263.                 return field;  
  264.             } catch (NoSuchFieldException e) {  
  265.                 // ignore and search next  
  266.             }  
  267.         }  
  268.   
  269.         throw new NoSuchFieldException("Field " + name + " not found in " + instance.getClass());  
  270.     }  
  271.   
  272.     /** 
  273.      * Locates a given method anywhere in the class inheritance hierarchy. 
  274.      * 
  275.      * @param instance an object to search the method into. 
  276.      * @param name method name 
  277.      * @param parameterTypes method parameter types 
  278.      * @return a method object 
  279.      * @throws NoSuchMethodException if the method cannot be located 
  280.      */  
  281.     private static Method findMethod(Object instance, String name, Class<?>... parameterTypes)  
  282.             throws NoSuchMethodException {  
  283.         for (Class<?> clazz = instance.getClass(); clazz != null; clazz = clazz.getSuperclass()) {  
  284.             try {  
  285.                 Method method = clazz.getDeclaredMethod(name, parameterTypes);  
  286.   
  287.   
  288.                 if (!method.isAccessible()) {  
  289.                     method.setAccessible(true);  
  290.                 }  
  291.   
  292.                 return method;  
  293.             } catch (NoSuchMethodException e) {  
  294.                 // ignore and search next  
  295.             }  
  296.         }  
  297.   
  298.         throw new NoSuchMethodException("Method " + name + " with parameters " +  
  299.                 Arrays.asList(parameterTypes) + " not found in " + instance.getClass());  
  300.     }  
  301.   
  302.     /** 
  303.      * Replace the value of a field containing a non null array, by a new array containing the 
  304.      * elements of the original array plus the elements of extraElements. 
  305.      * @param instance the instance whose field is to be modified. 
  306.      * @param fieldName the field to modify. 
  307.      * @param extraElements elements to append at the end of the array. 
  308.      */  
  309.     private static void expandFieldArray(Object instance, String fieldName,  
  310.             Object[] extraElements) throws NoSuchFieldException, IllegalArgumentException,  
  311.             IllegalAccessException {  
  312.         Field jlrField = findField(instance, fieldName);  
  313.         Object[] original = (Object[]) jlrField.get(instance);  
  314.         Object[] combined = (Object[]) Array.newInstance(  
  315.                 original.getClass().getComponentType(), original.length + extraElements.length);  
  316.         System.arraycopy(original, 0, combined, 0, original.length);  
  317.         System.arraycopy(extraElements, 0, combined, original.length, extraElements.length);  
  318.         jlrField.set(instance, combined);  
  319.     }  
  320.   
  321.     private static void clearOldDexDir(Context context) throws Exception {  
  322.         File dexDir = new File(context.getFilesDir(), OLD_SECONDARY_FOLDER_NAME);  
  323.         if (dexDir.isDirectory()) {  
  324.             Log.i(TAG, "Clearing old secondary dex dir (" + dexDir.getPath() + ").");  
  325.             File[] files = dexDir.listFiles();  
  326.             if (files == null) {  
  327.                 Log.w(TAG, "Failed to list secondary dex dir content (" + dexDir.getPath() + ").");  
  328.                 return;  
  329.             }  
  330.             for (File oldFile : files) {  
  331.                 Log.i(TAG, "Trying to delete old file " + oldFile.getPath() + " of size "  
  332.                         + oldFile.length());  
  333.                 if (!oldFile.delete()) {  
  334.                     Log.w(TAG, "Failed to delete old file " + oldFile.getPath());  
  335.                 } else {  
  336.                     Log.i(TAG, "Deleted old file " + oldFile.getPath());  
  337.                 }  
  338.             }  
  339.             if (!dexDir.delete()) {  
  340.                 Log.w(TAG, "Failed to delete secondary dex dir " + dexDir.getPath());  
  341.             } else {  
  342.                 Log.i(TAG, "Deleted old secondary dex dir " + dexDir.getPath());  
  343.             }  
  344.         }  
  345.     }  
  346.   
  347.     /** 
  348.      * Installer for platform versions 19. 
  349.      */  
  350.     private static final class V19 {  
  351.   
  352.         private static void install(ClassLoader loader, List<File> additionalClassPathEntries,  
  353.                 File optimizedDirectory)  
  354.                         throws IllegalArgumentException, IllegalAccessException,  
  355.                         NoSuchFieldException, InvocationTargetException, NoSuchMethodException {  
  356.             /* The patched class loader is expected to be a descendant of 
  357.              * dalvik.system.BaseDexClassLoader. We modify its 
  358.              * dalvik.system.DexPathList pathList field to append additional DEX 
  359.              * file entries. 
  360.              */  
  361.             Field pathListField = findField(loader, "pathList");  
  362.             Object dexPathList = pathListField.get(loader);  
  363.             ArrayList<IOException> suppressedExceptions = new ArrayList<IOException>();  
  364.             expandFieldArray(dexPathList, "dexElements", makeDexElements(dexPathList,  
  365.                     new ArrayList<File>(additionalClassPathEntries), optimizedDirectory,  
  366.                     suppressedExceptions));  
  367.             if (suppressedExceptions.size() > 0) {  
  368.                 for (IOException e : suppressedExceptions) {  
  369.                     Log.w(TAG, "Exception in makeDexElement", e);  
  370.                 }  
  371.                 Field suppressedExceptionsField =  
  372.                         findField(loader, "dexElementsSuppressedExceptions");  
  373.                 IOException[] dexElementsSuppressedExceptions =  
  374.                         (IOException[]) suppressedExceptionsField.get(loader);  
  375.   
  376.                 if (dexElementsSuppressedExceptions == null) {  
  377.                     dexElementsSuppressedExceptions =  
  378.                             suppressedExceptions.toArray(  
  379.                                     new IOException[suppressedExceptions.size()]);  
  380.                 } else {  
  381.                     IOException[] combined =  
  382.                             new IOException[suppressedExceptions.size() +  
  383.                                             dexElementsSuppressedExceptions.length];  
  384.                     suppressedExceptions.toArray(combined);  
  385.                     System.arraycopy(dexElementsSuppressedExceptions, 0, combined,  
  386.                             suppressedExceptions.size(), dexElementsSuppressedExceptions.length);  
  387.                     dexElementsSuppressedExceptions = combined;  
  388.                 }  
  389.   
  390.                 suppressedExceptionsField.set(loader, dexElementsSuppressedExceptions);  
  391.             }  
  392.         }  
  393.   
  394.         /** 
  395.          * A wrapper around 
  396.          * {@code private static final dalvik.system.DexPathList#makeDexElements}. 
  397.          */  
  398.         private static Object[] makeDexElements(  
  399.                 Object dexPathList, ArrayList<File> files, File optimizedDirectory,  
  400.                 ArrayList<IOException> suppressedExceptions)  
  401.                         throws IllegalAccessException, InvocationTargetException,  
  402.                         NoSuchMethodException {  
  403.             Method makeDexElements =  
  404.                     findMethod(dexPathList, "makeDexElements", ArrayList.class, File.class,  
  405.                             ArrayList.class);  
  406.   
  407.             return (Object[]) makeDexElements.invoke(dexPathList, files, optimizedDirectory,  
  408.                     suppressedExceptions);  
  409.         }  
  410.     }  
  411.   
  412.     /** 
  413.      * Installer for platform versions 14, 15, 16, 17 and 18. 
  414.      */  
  415.     private static final class V14 {  
  416.   
  417.         private static void install(ClassLoader loader, List<File> additionalClassPathEntries,  
  418.                 File optimizedDirectory)  
  419.                         throws IllegalArgumentException, IllegalAccessException,  
  420.                         NoSuchFieldException, InvocationTargetException, NoSuchMethodException {  
  421.             /* The patched class loader is expected to be a descendant of 
  422.              * dalvik.system.BaseDexClassLoader. We modify its 
  423.              * dalvik.system.DexPathList pathList field to append additional DEX 
  424.              * file entries. 
  425.              */  
  426.             Field pathListField = findField(loader, "pathList");  
  427.             Object dexPathList = pathListField.get(loader);  
  428.             expandFieldArray(dexPathList, "dexElements", makeDexElements(dexPathList,  
  429.                     new ArrayList<File>(additionalClassPathEntries), optimizedDirectory));  
  430.         }  
  431.   
  432.         /** 
  433.          * A wrapper around 
  434.          * {@code private static final dalvik.system.DexPathList#makeDexElements}. 
  435.          */  
  436.         private static Object[] makeDexElements(  
  437.                 Object dexPathList, ArrayList<File> files, File optimizedDirectory)  
  438.                         throws IllegalAccessException, InvocationTargetException,  
  439.                         NoSuchMethodException {  
  440.             Method makeDexElements =  
  441.                     findMethod(dexPathList, "makeDexElements", ArrayList.class, File.class);  
  442.   
  443.             return (Object[]) makeDexElements.invoke(dexPathList, files, optimizedDirectory);  
  444.         }  
  445.     }  
  446.   
  447.     /** 
  448.      * Installer for platform versions 4 to 13. 
  449.      */  
  450.     private static final class V4 {  
  451.         private static void install(ClassLoader loader, List<File> additionalClassPathEntries)  
  452.                         throws IllegalArgumentException, IllegalAccessException,  
  453.                         NoSuchFieldException, IOException {  
  454.             /* The patched class loader is expected to be a descendant of 
  455.              * dalvik.system.DexClassLoader. We modify its 
  456.              * fields mPaths, mFiles, mZips and mDexs to append additional DEX 
  457.              * file entries. 
  458.              */  
  459.             int extraSize = additionalClassPathEntries.size();  
  460.   
  461.             Field pathField = findField(loader, "path");  
  462.   
  463.             StringBuilder path = new StringBuilder((String) pathField.get(loader));  
  464.             String[] extraPaths = new String[extraSize];  
  465.             File[] extraFiles = new File[extraSize];  
  466.             ZipFile[] extraZips = new ZipFile[extraSize];  
  467.             DexFile[] extraDexs = new DexFile[extraSize];  
  468.             for (ListIterator<File> iterator = additionalClassPathEntries.listIterator();  
  469.                     iterator.hasNext();) {  
  470.                 File additionalEntry = iterator.next();  
  471.                 String entryPath = additionalEntry.getAbsolutePath();  
  472.                 path.append(':').append(entryPath);  
  473.                 int index = iterator.previousIndex();  
  474.                 extraPaths[index] = entryPath;  
  475.                 extraFiles[index] = additionalEntry;  
  476.                 extraZips[index] = new ZipFile(additionalEntry);  
  477.                 extraDexs[index] = DexFile.loadDex(entryPath, entryPath + ".dex"0);  
  478.             }  
  479.   
  480.             pathField.set(loader, path.toString());  
  481.             expandFieldArray(loader, "mPaths", extraPaths);  
  482.             expandFieldArray(loader, "mFiles", extraFiles);  
  483.             expandFieldArray(loader, "mZips", extraZips);  
  484.             expandFieldArray(loader, "mDexs", extraDexs);  
  485.         }  
  486.     }  
  487.   
  488. }  
MultiDexApplication类
[java]  view plain  copy
  1. import android.app.Application;  
  2. import android.content.Context;  
  3.   
  4. /** 
  5.  * * Minimal MultiDex capable application. To use the legacy multidex library 
  6.  * there is 3 possibility: 24 * 
  7.  * <ul> 
  8.  * * 
  9.  * <li>Declare this class as the application in your AndroidManifest.xml.</li> 
  10.  * * 
  11.  * <li>Have your {@link Application} extends this class.</li> 
  12.  * * 
  13.  * <li>Have your {@link Application} override attachBaseContext starting with<br> 
  14.  * * <code> 
  15.   protected void attachBaseContext(Context base) {<br> 
  16.      super.attachBaseContext(base);<br> 
  17.      MultiDex.install(this); 
  18.     </code></li> 3 * 
  19.  * <ul> 
  20.  */  
  21. public class MultiDexApplication extends Application {  
  22.     @Override  
  23.     protected void attachBaseContext(Context base) {  
  24.         super.attachBaseContext(base);  
  25.         MultiDex.install(this);  
  26.     }  
  27. }  
MultiDexExtractor类
[java]  view plain  copy
  1. import java.io.BufferedOutputStream;  
  2. import java.io.Closeable;  
  3. import java.io.File;  
  4. import java.io.FileFilter;  
  5. import java.io.FileNotFoundException;  
  6. import java.io.FileOutputStream;  
  7. import java.io.IOException;  
  8. import java.io.InputStream;  
  9. import java.lang.reflect.InvocationTargetException;  
  10. import java.lang.reflect.Method;  
  11. import java.util.ArrayList;  
  12. import java.util.List;  
  13. import java.util.zip.ZipEntry;  
  14. import java.util.zip.ZipException;  
  15. import java.util.zip.ZipFile;  
  16. import java.util.zip.ZipOutputStream;  
  17.   
  18. import android.content.Context;  
  19. import android.content.SharedPreferences;  
  20. import android.content.pm.ApplicationInfo;  
  21. import android.os.Build;  
  22. import android.util.Log;  
  23.   
  24. /** 
  25.  * Exposes application secondary dex files as files in the application data 
  26.  * directory. 
  27.  */  
  28. final class MultiDexExtractor {  
  29.   
  30.     private static final String TAG = MultiDex.TAG;  
  31.   
  32.     /** 
  33.      * We look for additional dex files named {@code classes2.dex}, 
  34.      * {@code classes3.dex}, etc. 
  35.      */  
  36.     private static final String DEX_PREFIX = "classes";  
  37.     private static final String DEX_SUFFIX = ".dex";  
  38.   
  39.     private static final String EXTRACTED_NAME_EXT = ".classes";  
  40.     private static final String EXTRACTED_SUFFIX = ".zip";  
  41.     private static final int MAX_EXTRACT_ATTEMPTS = 3;  
  42.   
  43.     private static final String PREFS_FILE = "multidex.version";  
  44.     private static final String KEY_TIME_STAMP = "timestamp";  
  45.     private static final String KEY_CRC = "crc";  
  46.     private static final String KEY_DEX_NUMBER = "dex.number";  
  47.   
  48.     /** 
  49.      * Size of reading buffers. 
  50.      */  
  51.     private static final int BUFFER_SIZE = 0x4000;  
  52.     /* Keep value away from 0 because it is a too probable time stamp value */  
  53.     private static final long NO_VALUE = -1L;  
  54.   
  55.     /** 
  56.      * Extracts application secondary dexes into files in the application data 
  57.      * directory. 
  58.      *  
  59.      * @return a list of files that were created. The list may be empty if there 
  60.      *         are no secondary dex files. 
  61.      * @throws IOException 
  62.      *             if encounters a problem while reading or writing secondary 
  63.      *             dex files 
  64.      */  
  65.     static List<File> load(Context context, ApplicationInfo applicationInfo,  
  66.             File dexDir, boolean forceReload) throws IOException {  
  67.         Log.i(TAG, "MultiDexExtractor.load(" + applicationInfo.sourceDir + ", "  
  68.                 + forceReload + ")");  
  69.         final File sourceApk = new File(applicationInfo.sourceDir);  
  70.         long currentCrc = getZipCrc(sourceApk);  
  71.   
  72.         List<File> files;  
  73.         if (!forceReload && !isModified(context, sourceApk, currentCrc)) {  
  74.             try {  
  75.                 files = loadExistingExtractions(context, sourceApk, dexDir);  
  76.             } catch (IOException ioe) {  
  77.                 Log.w(TAG,  
  78.                         "Failed to reload existing extracted secondary dex files,"  
  79.                                 + " falling back to fresh extraction", ioe);  
  80.                 files = performExtractions(sourceApk, dexDir);  
  81.                 putStoredApkInfo(context, getTimeStamp(sourceApk), currentCrc,  
  82.                         files.size() + 1);  
  83.   
  84.             }  
  85.         } else {  
  86.             Log.i(TAG, "Detected that extraction must be performed.");  
  87.             files = performExtractions(sourceApk, dexDir);  
  88.             putStoredApkInfo(context, getTimeStamp(sourceApk), currentCrc,  
  89.                     files.size() + 1);  
  90.         }  
  91.   
  92.         Log.i(TAG, "load found " + files.size() + " secondary dex files");  
  93.         return files;  
  94.     }  
  95.   
  96.     private static List<File> loadExistingExtractions(Context context,  
  97.             File sourceApk, File dexDir) throws IOException {  
  98.         Log.i(TAG, "loading existing secondary dex files");  
  99.   
  100.         final String extractedFilePrefix = sourceApk.getName()  
  101.                 + EXTRACTED_NAME_EXT;  
  102.         int totalDexNumber = getMultiDexPreferences(context).getInt(  
  103.                 KEY_DEX_NUMBER, 1);  
  104.         final List<File> files = new ArrayList<File>(totalDexNumber);  
  105.   
  106.         for (int secondaryNumber = 2; secondaryNumber <= totalDexNumber; secondaryNumber++) {  
  107.             String fileName = extractedFilePrefix + secondaryNumber  
  108.                     + EXTRACTED_SUFFIX;  
  109.             File extractedFile = new File(dexDir, fileName);  
  110.             if (extractedFile.isFile()) {  
  111.                 files.add(extractedFile);  
  112.                 if (!verifyZipFile(extractedFile)) {  
  113.                     Log.i(TAG, "Invalid zip file: " + extractedFile);  
  114.                     throw new IOException("Invalid ZIP file.");  
  115.                 }  
  116.             } else {  
  117.                 throw new IOException("Missing extracted secondary dex file ‘"  
  118.                         + extractedFile.getPath() + "‘");  
  119.             }  
  120.         }  
  121.   
  122.         return files;  
  123.     }  
  124.   
  125.     private static boolean isModified(Context context, File archive,  
  126.             long currentCrc) {  
  127.         SharedPreferences prefs = getMultiDexPreferences(context);  
  128.         return (prefs.getLong(KEY_TIME_STAMP, NO_VALUE) != getTimeStamp(archive))  
  129.                 || (prefs.getLong(KEY_CRC, NO_VALUE) != currentCrc);  
  130.     }  
  131.   
  132.     private static long getTimeStamp(File archive) {  
  133.         long timeStamp = archive.lastModified();  
  134.         if (timeStamp == NO_VALUE) {  
  135.             // never return NO_VALUE  
  136.             timeStamp--;  
  137.         }  
  138.         return timeStamp;  
  139.     }  
  140.   
  141.     private static long getZipCrc(File archive) throws IOException {  
  142.         long computedValue = ZipUtil.getZipCrc(archive);  
  143.         if (computedValue == NO_VALUE) {  
  144.             // never return NO_VALUE  
  145.             computedValue--;  
  146.         }  
  147.         return computedValue;  
  148.     }  
  149.   
  150.     private static List<File> performExtractions(File sourceApk, File dexDir)  
  151.             throws IOException {  
  152.   
  153.         final String extractedFilePrefix = sourceApk.getName()  
  154.                 + EXTRACTED_NAME_EXT;  
  155.   
  156.         // Ensure that whatever deletions happen in prepareDexDir only happen if  
  157.         // the zip that  
  158.         // contains a secondary dex file in there is not consistent with the  
  159.         // latest apk. Otherwise,  
  160.         // multi-process race conditions can cause a crash loop where one  
  161.         // process deletes the zip  
  162.         // while another had created it.  
  163.         prepareDexDir(dexDir, extractedFilePrefix);  
  164.   
  165.         List<File> files = new ArrayList<File>();  
  166.   
  167.         final ZipFile apk = new ZipFile(sourceApk);  
  168.         try {  
  169.   
  170.             int secondaryNumber = 2;  
  171.   
  172.             ZipEntry dexFile = apk.getEntry(DEX_PREFIX + secondaryNumber  
  173.                     + DEX_SUFFIX);  
  174.             while (dexFile != null) {  
  175.                 String fileName = extractedFilePrefix + secondaryNumber  
  176.                         + EXTRACTED_SUFFIX;  
  177.                 File extractedFile = new File(dexDir, fileName);  
  178.                 files.add(extractedFile);  
  179.   
  180.                 Log.i(TAG, "Extraction is needed for file " + extractedFile);  
  181.                 int numAttempts = 0;  
  182.                 boolean isExtractionSuccessful = false;  
  183.                 while (numAttempts < MAX_EXTRACT_ATTEMPTS  
  184.                         && !isExtractionSuccessful) {  
  185.                     numAttempts++;  
  186.   
  187.                     // Create a zip file (extractedFile) containing only the  
  188.                     // secondary dex file  
  189.                     // (dexFile) from the apk.  
  190.                     extract(apk, dexFile, extractedFile, extractedFilePrefix);  
  191.   
  192.                     // Verify that the extracted file is indeed a zip file.  
  193.                     isExtractionSuccessful = verifyZipFile(extractedFile);  
  194.   
  195.                     // Log the sha1 of the extracted zip file  
  196.                     Log.i(TAG, "Extraction "  
  197.                             + (isExtractionSuccessful ? "success" : "failed")  
  198.                             + " - length " + extractedFile.getAbsolutePath()  
  199.                             + ": " + extractedFile.length());  
  200.                     if (!isExtractionSuccessful) {  
  201.                         // Delete the extracted file  
  202.                         extractedFile.delete();  
  203.                         if (extractedFile.exists()) {  
  204.                             Log.w(TAG,  
  205.                                     "Failed to delete corrupted secondary dex ‘"  
  206.                                             + extractedFile.getPath() + "‘");  
  207.                         }  
  208.                     }  
  209.                 }  
  210.                 if (!isExtractionSuccessful) {  
  211.                     throw new IOException("Could not create zip file "  
  212.                             + extractedFile.getAbsolutePath()  
  213.                             + " for secondary dex (" + secondaryNumber + ")");  
  214.                 }  
  215.                 secondaryNumber++;  
  216.                 dexFile = apk.getEntry(DEX_PREFIX + secondaryNumber  
  217.                         + DEX_SUFFIX);  
  218.             }  
  219.         } finally {  
  220.             try {  
  221.                 apk.close();  
  222.             } catch (IOException e) {  
  223.                 Log.w(TAG, "Failed to close resource", e);  
  224.             }  
  225.         }  
  226.   
  227.         return files;  
  228.     }  
  229.   
  230.     private static void putStoredApkInfo(Context context, long timeStamp,  
  231.             long crc, int totalDexNumber) {  
  232.         SharedPreferences prefs = getMultiDexPreferences(context);  
  233.         SharedPreferences.Editor edit = prefs.edit();  
  234.         edit.putLong(KEY_TIME_STAMP, timeStamp);  
  235.         edit.putLong(KEY_CRC, crc);  
  236.         /* 
  237.          * SharedPreferences.Editor doc says that apply() and commit() 
  238.          * "atomically performs the requested modifications" it should be OK to 
  239.          * rely on saving the dex files number (getting old number value would 
  240.          * go along with old crc and time stamp). 
  241.          */  
  242.         edit.putInt(KEY_DEX_NUMBER, totalDexNumber);  
  243.         apply(edit);  
  244.     }  
  245.   
  246.     private static SharedPreferences getMultiDexPreferences(Context context) {  
  247.         return context  
  248.                 .getSharedPreferences(  
  249.                         PREFS_FILE,  
  250.                         Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB ? Context.MODE_PRIVATE  
  251.                                 : Context.MODE_PRIVATE  
  252.                                         | Context.MODE_MULTI_PROCESS);  
  253.     }  
  254.   
  255.     /** 
  256.      * This removes any files that do not have the correct prefix. 
  257.      */  
  258.     private static void prepareDexDir(File dexDir,  
  259.             final String extractedFilePrefix) throws IOException {  
  260.         dexDir.mkdirs();  
  261.         if (!dexDir.isDirectory()) {  
  262.             throw new IOException("Failed to create dex directory "  
  263.                     + dexDir.getPath());  
  264.         }  
  265.   
  266.         // Clean possible old files  
  267.         FileFilter filter = new FileFilter() {  
  268.   
  269.             @Override  
  270.             public boolean accept(File pathname) {  
  271.                 return !pathname.getName().startsWith(extractedFilePrefix);  
  272.             }  
  273.         };  
  274.         File[] files = dexDir.listFiles(filter);  
  275.         if (files == null) {  
  276.             Log.w(TAG,  
  277.                     "Failed to list secondary dex dir content ("  
  278.                             + dexDir.getPath() + ").");  
  279.             return;  
  280.         }  
  281.         for (File oldFile : files) {  
  282.             Log.i(TAG, "Trying to delete old file " + oldFile.getPath()  
  283.                     + " of size " + oldFile.length());  
  284.             if (!oldFile.delete()) {  
  285.                 Log.w(TAG, "Failed to delete old file " + oldFile.getPath());  
  286.             } else {  
  287.                 Log.i(TAG, "Deleted old file " + oldFile.getPath());  
  288.             }  
  289.         }  
  290.     }  
  291.   
  292.     private static void extract(ZipFile apk, ZipEntry dexFile, File extractTo,  
  293.             String extractedFilePrefix) throws IOException,  
  294.             FileNotFoundException {  
  295.   
  296.         InputStream in = apk.getInputStream(dexFile);  
  297.         ZipOutputStream out = null;  
  298.         File tmp = File.createTempFile(extractedFilePrefix, EXTRACTED_SUFFIX,  
  299.                 extractTo.getParentFile());  
  300.         Log.i(TAG, "Extracting " + tmp.getPath());  
  301.         try {  
  302.             out = new ZipOutputStream(new BufferedOutputStream(  
  303.                     new FileOutputStream(tmp)));  
  304.             try {  
  305.                 ZipEntry classesDex = new ZipEntry("classes.dex");  
  306.                 // keep zip entry time since it is the criteria used by Dalvik  
  307.                 classesDex.setTime(dexFile.getTime());  
  308.                 out.putNextEntry(classesDex);  
  309.   
  310.                 byte[] buffer = new byte[BUFFER_SIZE];  
  311.                 int length = in.read(buffer);  
  312.                 while (length != -1) {  
  313.                     out.write(buffer, 0, length);  
  314.                     length = in.read(buffer);  
  315.                 }  
  316.                 out.closeEntry();  
  317.             } finally {  
  318.                 out.close();  
  319.             }  
  320.             Log.i(TAG, "Renaming to " + extractTo.getPath());  
  321.             if (!tmp.renameTo(extractTo)) {  
  322.                 throw new IOException("Failed to rename \""  
  323.                         + tmp.getAbsolutePath() + "\" to \""  
  324.                         + extractTo.getAbsolutePath() + "\"");  
  325.             }  
  326.         } finally {  
  327.             closeQuietly(in);  
  328.             tmp.delete(); // return status ignored  
  329.         }  
  330.     }  
  331.   
  332.     /** 
  333.      * Returns whether the file is a valid zip file. 
  334.      */  
  335.     static boolean verifyZipFile(File file) {  
  336.         try {  
  337.             ZipFile zipFile = new ZipFile(file);  
  338.             try {  
  339.                 zipFile.close();  
  340.                 return true;  
  341.             } catch (IOException e) {  
  342.                 Log.w(TAG,  
  343.                         "Failed to close zip file: " + file.getAbsolutePath());  
  344.             }  
  345.         } catch (ZipException ex) {  
  346.             Log.w(TAG, "File " + file.getAbsolutePath()  
  347.                     + " is not a valid zip file.", ex);  
  348.         } catch (IOException ex) {  
  349.             Log.w(TAG,  
  350.                     "Got an IOException trying to open zip file: "  
  351.                             + file.getAbsolutePath(), ex);  
  352.         }  
  353.         return false;  
  354.     }  
  355.   
  356.     /** 
  357.      * Closes the given {@code Closeable}. Suppresses any IO exceptions. 
  358.      */  
  359.     private static void closeQuietly(Closeable closeable) {  
  360.         try {  
  361.             closeable.close();  
  362.         } catch (IOException e) {  
  363.             Log.w(TAG, "Failed to close resource", e);  
  364.         }  
  365.     }  
  366.   
  367.     // The following is taken from SharedPreferencesCompat to avoid having a  
  368.     // dependency of the  
  369.     // multidex support library on another support library.  
  370.     private static Method sApplyMethod; // final  
  371.     static {  
  372.         try {  
  373.             Class<?> cls = SharedPreferences.Editor.class;  
  374.             sApplyMethod = cls.getMethod("apply");  
  375.         } catch (NoSuchMethodException unused) {  
  376.             sApplyMethod = null;  
  377.         }  
  378.     }  
  379.   
  380.     private static void apply(SharedPreferences.Editor editor) {  
  381.         if (sApplyMethod != null) {  
  382.             try {  
  383.                 sApplyMethod.invoke(editor);  
  384.                 return;  
  385.             } catch (InvocationTargetException unused) {  
  386.                 // fall through  
  387.             } catch (IllegalAccessException unused) {  
  388.                 // fall through  
  389.             }  
  390.         }  
  391.         editor.commit();  
  392.     }  
  393. }  
ZipUtil类
[java]  view plain  copy
  1. import java.io.File;  
  2.  import java.io.IOException;  
  3.  import java.io.RandomAccessFile;  
  4.  import java.util.zip.CRC32;  
  5.  import java.util.zip.ZipException;  
  6.    
  7. /** 
  8.    * Tools to build a quick partial crc of zip files. 
  9.   */  
  10.  final class ZipUtil {  
  11.     static class CentralDirectory {  
  12.          long offset;  
  13.          long size;  
  14.      }  
  15.    
  16.      /* redefine those constant here because of bug 13721174 preventing to compile using the 
  17.      * constants defined in ZipFile */  
  18.      private static final int ENDHDR = 22;  
  19.      private static final int ENDSIG = 0x6054b50;  
  20.   
  21.     /** 
  22.       * Size of reading buffers. 
  23.       */  
  24.      private static final int BUFFER_SIZE = 0x4000;  
  25.     
  26.      /** 
  27.       * Compute crc32 of the central directory of an apk. The central directory contains 
  28.       * the crc32 of each entries in the zip so the computed result is considered valid for the whole 
  29.        * zip file. Does not support zip64 nor multidisk but it should be OK for now since ZipFile does 
  30.      * not either. 
  31.       */  
  32.     static long getZipCrc(File apk) throws IOException {  
  33.         RandomAccessFile raf = new RandomAccessFile(apk, "r");  
  34.         try {  
  35.             CentralDirectory dir = findCentralDirectory(raf);  
  36.   
  37.            return computeCrcOfCentralDir(raf, dir);  
  38.          } finally {  
  39.            raf.close();  
  40.         }  
  41.     }  
  42.   
  43.   /* Package visible for testing */  
  44.      static CentralDirectory findCentralDirectory(RandomAccessFile raf) throws IOException,  
  45.             ZipException {  
  46.          long scanOffset = raf.length() - ENDHDR;  
  47.         if (scanOffset < 0) {  
  48.             throw new ZipException("File too short to be a zip file: " + raf.length());  
  49.        }  
  50.   
  51.        long stopOffset = scanOffset - 0x10000 /* ".ZIP file comment"‘s max length */;  
  52.        if (stopOffset < 0) {  
  53.             stopOffset = 0;  
  54.      }  
  55.   
  56.         int endSig = Integer.reverseBytes(ENDSIG);  
  57.        while (true) {  
  58.             raf.seek(scanOffset);  
  59.         if (raf.readInt() == endSig) {  
  60.                break;  
  61.            }  
  62.   
  63.             scanOffset--;  
  64.              if (scanOffset < stopOffset) {  
  65.                throw new ZipException("End Of Central Directory signature not found");  
  66.            }  
  67.         }  
  68.         // Read the End Of Central Directory. ENDHDR includes the signature  
  69.         // bytes,  
  70.        // which we‘ve already read.  
  71.   
  72.         // Pull out the information we need.  
  73.          raf.skipBytes(2); // diskNumber  
  74.         raf.skipBytes(2); // diskWithCentralDir  
  75.         raf.skipBytes(2); // numEntries  
  76.         raf.skipBytes(2); // totalNumEntries  
  77.          CentralDirectory dir = new CentralDirectory();  
  78.        dir.size = Integer.reverseBytes(raf.readInt()) & 0xFFFFFFFFL;  
  79.        dir.offset = Integer.reverseBytes(raf.readInt()) & 0xFFFFFFFFL;  
  80.        return dir;  
  81.      }  
  82.   
  83.      /* Package visible for testing */  
  84.     static long computeCrcOfCentralDir(RandomAccessFile raf, CentralDirectory dir)  
  85.              throws IOException {  
  86.         CRC32 crc = new CRC32();  
  87.         long stillToRead = dir.size;  
  88.         raf.seek(dir.offset);  
  89.         int length = (int) Math.min(BUFFER_SIZE, stillToRead);  
  90.        byte[] buffer = new byte[BUFFER_SIZE];  
  91.         length = raf.read(buffer, 0, length);  
  92.         while (length != -1) {  
  93.             crc.update(buffer, 0, length);  
  94.              stillToRead -= length;  
  95.             if (stillToRead == 0) {  
  96.                 break;  
  97.             }  
  98.              length = (int) Math.min(BUFFER_SIZE, stillToRead);  
  99.             length = raf.read(buffer, 0, length);  
  100.         }  
  101.         return crc.getValue();  
  102.     }  
  103. }  

最后还是感谢这http://www.mamicode.com/info-detail-1578920.html、http://blog.csdn.net/lxlyhm/article/details/52608190这两篇文章博主
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值