2

我想使用 ApplicationWrapepr 方法在我的应用程序中使用 multidex,如此处所述https://plus.google.com/104023661970539138053/posts/YTMf8ADTcFg

我使用了 --minimal-main-dex 选项以及这样的保留文件:

android/support/multidex/ZipUtil.class
android/support/multidex/ZipUtil$CentralDirectory.class
android/support/multidex/MultiDex$V14.class
android/support/multidex/MultiDexExtractor$1.class
android/support/multidex/MultiDexExtractor.class
com/<mypackage>/common/MyApplication.class
com/<mypackage>/common/MyApplicationWrapper.class
com/<mypackage>/common/ui/DashboardActivity.class
android/support/multidex/MultiDexApplication.class
android/support/multidex/MultiDex.class
android/support/multidex/MultiDex$V19.class
android/support/multidex/MultiDex$V4.class

这导致在我的主 dex 文件中列出的类是可以的。我比使用使用以下代码的库来列出 dexfile 中的所有类,但只获取主“clesses.dex”的条目,而不是所有其他加载的 dex 文件的条目,因为新的 DexFile 只检查“classes.dex” :

private static List<String> getPaths(final String[] sourcePaths) {
    List<String> result = new ArrayList<String>();

    for (String s : sourcePaths) {
      try {
        DexFile dexfile = new DexFile(s);
        Enumeration<String> entries = dexfile.entries();

        while (entries.hasMoreElements()) {
          result.add(entries.nextElement());
        }
      } catch (IOException ioe) {
        Log.w(TAG, "cannot open file=" + s + ";Exception=" + ioe.getMessage());
      }
    }

    return result;
}

目前的单一路径通过以下方式确定:

application.getApplicationContext().getApplicationInfo().sourceDir;

结果类似于 /data/../myapplicationname.apk

是否有另一种可能列出 dex 文件中的所有类?或者当前在 ClassLoaders 中的所有类?该库对项目至关重要,并在以后使用这种方法通过反射查找组件实现。

EDIT1: 如果发现classes2.dex文件位于:/data/data/com./code_cache/secondary-dexes/com.-1.apk.classes2.dex

但是,当使用带有此路径的 new DexFile() 时,IOEsxception 会抛出消息“无法打开 dexfile”。

4

3 回答 3

6

DexFile 接受 zip/apk 文件的路径,并将其解压缩以找到 .dex 文件。所以如果你使用 .dex 作为路径,它会抛出一个错误。

谷歌还发布了一篇文章使用超过 65K 方法构建应用程序来解决 --multi-dex 问题。

我写了一个类来加载所有的类。你可以阅读更多:http: //xudshen.info/2014/11/12/list-all-classes-after-multidex/

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;

/**
 * Created by xudshen@hotmail.com on 14/11/13.
 */
public class MultiDexHelper {
    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 static 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 static List<String> getSourcePaths(Context context) throws PackageManager.NameNotFoundException, IOException {
        ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
        File sourceApk = new File(applicationInfo.sourceDir);
        File dexDir = new File(applicationInfo.dataDir, SECONDARY_FOLDER_NAME);

        List<String> sourcePaths = new ArrayList<String>();
        sourcePaths.add(applicationInfo.sourceDir); //add the default apk path

        //the prefix of extracted file, ie: test.classes
        String extractedFilePrefix = sourceApk.getName() + EXTRACTED_NAME_EXT;
        //the total dex numbers
        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...
            String fileName = extractedFilePrefix + secondaryNumber + EXTRACTED_SUFFIX;
            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 classes name in "classes.dex", "classes2.dex", ....
     *
     * @param context the application context
     * @return all the classes name
     * @throws PackageManager.NameNotFoundException
     * @throws IOException
     */
    public static List<String> getAllClasses(Context context) throws PackageManager.NameNotFoundException, IOException {
        List<String> classNames = new ArrayList<String>();
        for (String path : getSourcePaths(context)) {
            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);
                }
                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;
    }
}
于 2014-11-12T17:13:58.790 回答
1

如果您使用即时运行运行应用程序,则需要添加以下 DEX 文件路径:

// handle dex files built by instant run
        File instantRunFilePath = new File(applicationInfo.dataDir,
                                           "files" + File.separator + "instant-run" + File.separator + "dex");

        if (instantRunFilePath.exists() && instantRunFilePath.isDirectory()) {
            File[] sliceFiles = instantRunFilePath.listFiles();
            for (File sliceFile : sliceFiles) {
                if (null != sliceFile && sliceFile.exists() && sliceFile.isFile() && sliceFile.getName().endsWith(".dex")) {
                    sourcePaths.add(sliceFile.getAbsolutePath());
                }
            }
        }
于 2016-06-07T05:09:19.943 回答
1

我的解决方案适用于几乎所有情况,例如普通 apk、多 dex apk 或即时运行 apk。

这个想法来自multi-dex源代码。我使用反射来获取所有DexElementThread.currentThread().getContextClassLoader(),实际上它可以是任何其他类加载器。反射方式很棘手,因为该pathList字段不属于PathClassLoader但属于其超类。而且无论apk是multi-dex apk还是instant-run apk,该classLoader->pathList字段都包含了DexFile你需要查找的所有内容。并且列出 a 中的所有类DexFile并不太难。

这是代码:

    public static ArrayList<String> findClassesStartWith(String prefix) {
        try {
            ArrayList<String> result = new ArrayList<>();
            ArrayList<DexFile> dexFiles = findAllDexFiles(Thread.currentThread().getContextClassLoader());
            for (DexFile dexFile : dexFiles) {
                Enumeration<String> classNames = dexFile.entries();
                while (classNames.hasMoreElements()) {
                    String className = classNames.nextElement();
                    if (className.startsWith(prefix)) {
                        result.add(className);
                    }
                }
            }
            return result;
        } catch (Exception ignored) {
        }
        return null;
    }

    public static ArrayList<DexFile> findAllDexFiles(ClassLoader classLoader) {
        ArrayList<DexFile> dexFiles = new ArrayList<>();
        try {
            Field pathListField = findField(classLoader, "pathList");
            Object pathList = pathListField.get(classLoader);
            Field dexElementsField = findField(pathList, "dexElements");
            Object[] dexElements = (Object[]) dexElementsField.get(pathList);
            Field dexFileField = findField(dexElements[0], "dexFile");

            for (Object dexElement : dexElements) {
                Object dexFile = dexFileField.get(dexElement);
                dexFiles.add((DexFile) dexFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dexFiles;
    }

    private static Field findField(Object instance, String name) throws NoSuchFieldException {
        Class clazz = instance.getClass();

        while (clazz != null) {
            try {
                Field field = clazz.getDeclaredField(name);
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }

                return field;
            } catch (NoSuchFieldException var4) {
                clazz = clazz.getSuperclass();
            }
        }

        throw new NoSuchFieldException("Field " + name + " not found in " + instance.getClass());
    }
于 2019-02-27T01:59:10.313 回答