-3

I want to share some java files which can be common among different applications. Is it possible to share common java files across different android applications without changing in application gradle file (from apply plugin: 'com.android.application' to apply plugin: 'com.android.library') ?

Smita
  • 1

1 Answers1

0

Yes, you can. First, you shuld compile your Java class into jar file. Then you can load this jar using DexClassLoader, example:

CommonInterface loadCommonObject(String pathToJarFile) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
    DexClassLoader loader = new DexClassLoader(pathToJarFile,
            getDir("dex", 0).getAbsolutePath(), null, getClass().getClassLoader());
    Class clazz = loader.loadClass(CommonInterface.CLASS_NAME);
    return  (CommonInterface) clazz.newInstance();
}

interface CommonInterface {

    String CLASS_NAME = "com.your.app.ClassName";

    void doSomething();
}

And now you can use this code to load and run your Java file:

CommonInterface commonObject = loadCommonObject("/path/to/your/file.jar");
commonObject.doSomething();

Note, your jar file shuild be in DEX format. To convert plan jar file into DEX format you can use dx utility from Adnroid SDK.

More info in this question: Is it possible to dynamically load a library at runtime from an Android application?

Nikolay
  • 1,429
  • 1
  • 13
  • 24