Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gauravssnl/8a807d2f0d95e2285d7c201557955a17 to your computer and use it in GitHub Desktop.
Save gauravssnl/8a807d2f0d95e2285d7c201557955a17 to your computer and use it in GitHub Desktop.

Revisions

  1. @vvb2060 vvb2060 created this gist Jan 24, 2022.
    46 changes: 46 additions & 0 deletions InMemoryDexClassLoaderFactory.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,46 @@
    import android.app.AppComponentFactory;
    import android.content.pm.ApplicationInfo;
    import android.util.Log;

    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.channels.Channels;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.zip.ZipFile;

    import dalvik.system.InMemoryDexClassLoader;

    public class InMemoryDexClassLoaderFactory extends AppComponentFactory {

    private static ClassLoader classLoader;

    private static void readDexes(ZipFile apkFile, List<ByteBuffer> dexFiles) throws IOException {
    int secondary = 2;
    for (var dexFile = apkFile.getEntry("classes.dex"); dexFile != null;
    dexFile = apkFile.getEntry("classes" + secondary + ".dex"), secondary++) {
    var in = apkFile.getInputStream(dexFile);
    var byteBuffer = ByteBuffer.allocate(in.available());
    byteBuffer.mark();
    Channels.newChannel(in).read(byteBuffer);
    byteBuffer.reset();
    dexFiles.add(byteBuffer);
    }
    }

    @Override
    public ClassLoader instantiateClassLoader(ClassLoader cl, ApplicationInfo aInfo) {
    if (classLoader != null) return classLoader;
    var buffers = new ArrayList<ByteBuffer>();
    try (var zipFile = new ZipFile(aInfo.sourceDir)) {
    readDexes(zipFile, buffers);
    } catch (IOException e) {
    Log.e(App.TAG, "Can not load " + aInfo.sourceDir, e);
    return cl;
    }
    var dexfiles = new ByteBuffer[buffers.size()];
    buffers.toArray(dexfiles);
    classLoader = new InMemoryDexClassLoader(dexfiles, aInfo.nativeLibraryDir, cl.getParent());
    return classLoader;
    }
    }