0

I'm trying to load dynamically external classes using DexClassLoader, like @Shlublu proposes here

When I execute my application and the DexClassLoader object try to find the class, it throws a ClassNotFound exception. I have added read and write permissions in the manifest.xml, so it is not the mistake.

I think the problem is the method that I use to make the .jar that I want to load on my application. So I have some questions...

  • What is the correct method to convert a .java file to .jar using dx tool?
  • It is necessary that the package where the external class is loaded be the same that the package of my .jar file? (I think no)

I'm using an Android emulator API 19 (kit-kat)

Community
  • 1
  • 1
Angel C
  • 31
  • 4

1 Answers1

0

Since APK is the standard Android package, my suggestion is that you use an APK instead of a JAR. Build an application APK linking the needed JAR (let the Android build tools "dex" the JAR) but without any activity, then install the APK as if it was a normal app. You can then access the APK file itself using the PackageManager to get its path and load it using DexClassLoader.

public static ClassLoader loadAPK(final Context context, final String appName) throws PackageManager.NameNotFoundException {
    final String apkPath = context.getPackageManager().getApplicationInfo(appName, 0).sourceDir;
    final File tmpDir = context.getDir("tmp", 0);
    return new DexClassLoader(apkPath, tmpDir.getAbsolutePath(), null, context.getClassLoader());
}
m0skit0
  • 25,268
  • 11
  • 79
  • 127