is it possible to dynamically load a Activity class from a jar library on the sdCard & actually use it? is it possible to dynamically load a Activity class from a jar library on the sdCard & actually use it? android android

is it possible to dynamically load a Activity class from a jar library on the sdCard & actually use it?


I got similar scenarios.

If u do not put below codes in AndroidManifest.xml

<activity android:name="com.appno1.futureLib.LibActivity" android:label="@string/app_name" > </activity>

U will get below error.

10-21 17:04:25.860: E/AndroidRuntime(11050): Caused by: android.content.ActivityNotFoundException: Unable to find explicit activity class {... ...}; have you declared this activity in your AndroidManifest.xml?

But if u register the activity in your client application, then java.lang.ClassNotFoundException will be got.

The loader tried to search com.appno1.futureLib.LibActivity in [/data/app/com.appno2-1.apk]. Obviously this is not expected. I believed com.appno.futureLib.LibActivity is located in the .jar file.

If there is a way to let the loader to search LibActivity in the .jar file, the problem may be solved.


You can scan JAR files for their contents and load classes with URLClassloader. It is standard Java (I have a JavaSE implementation if you wish to take a look), but it is included in the Android API, so I think it should work fine.

URLClassloader on developer.android.com

Basically you get a ClassLoader (dirty code warning!):

File file = new File("/sdcard/jars/myDynamicLib.jar");ClassLoader loader = new URLClassLoader(new URL[]{file.toURI().toURL()}, this.getClass().getClassLoader());

you need your metadata XML or whatever describes what to load:

jar.getInputStream(jar.getEntry("myMetaData.xml"));

You load the information (the way you parse it depends on the format you use: you can have it already loaded with your app as well) - now you have the classname.

And now you just attempt loading:

Class<?> classref = Class.forName(className, true, loader);instance = (MyType) classref.getConstructor().newInstance();

Again, although I haven't tried such things on Droid, I think this should work fine.

That makes it up. You need the path to the JAR file, and the name of the class to load. The class loader will pull the classes out of the JAR for you.