我需要在 Android 项目的 main/assets 目录中放置一个 jar 文件。 jar 文件位于此处很重要。
对于我的主要 Android 项目,有没有一种方法可以在我的代码中引用这个 jar 文件并使用它的类?
需要说明的是,我不想在编译后将 jar 添加到主项目中。
编辑:我试过下面的链接,它似乎加载了我所说的类文件。但我正在研究如何为动态加载的类定义构造函数参数。
android-custom-class-loading-sample
EDIT2
快到了。我已经确认该类是从我的 classes.jar 中加载的。不过,我无法实例化它。
在 licenseValidatorClazz.getConstructor 行上,我收到以下错误。我猜我的界面文件中遗漏了什么?
java.lang.NoSuchMethodException:[接口(interface) com.google.android.vending.licensing.Policy,接口(interface) com.google.android.vending.licensing.DeviceLimiter,接口(interface) com.google.android.vending.licensing.LicenseCheckerCallback,int , 类 java.lang.String, 类 java.lang.String]
public Class licenseValidatorClazz = null;
public LicenseValidator validator;
...
// Initialize the class loader with the secondary dex file.
DexClassLoader cl = new DexClassLoader(dexInternalStoragePath.getAbsolutePath(),
optimizedDexOutputPath.getAbsolutePath(),
null,
mContext.getClassLoader());
try {
// Load the library class from the class loader.
licenseValidatorClazz = cl.loadClass("com.google.android.vending.licensing.LicenseValidator");
validator = (LicenseValidator) licenseValidatorClazz.getConstructor(Policy.class,DeviceLimiter.class,LicenseCheckerCallback.class,int.class,String.class,String.class).newInstance(ddd, new NullDeviceLimiter(),
callback, generateNonce(), mPackageName, mVersionCode);
} catch (Exception exception) {
// Handle exception gracefully here.
exception.printStackTrace();
}
我有一个接口(interface),其中包含传递给加载类的函数。
public interface LicenseValidator
{
public LicenseCheckerCallback getCallback();
public int getNonce();
public String getPackageName();
public void verify(PublicKey publicKey, int responseCode, String signedData, String signature);
public void handleResponse(int response, ResponseData rawData);
public void handleApplicationError(int code);
public void handleInvalidResponse();
}
最佳答案
要使用外部 jar 与您的应用程序关联并在运行时使用它,它需要采用 dalvik 格式,因为普通 jar 无法在 dalvikVM 下工作。
- 使用 dx 工具转换文件
- 使用 aapt cmd,将这些 classes.dex 添加到您的 jar 文件中。
- 现在这个包含dalvik格式文件的jar可以加载到我们的项目中了。
Here是一篇解释完成它的过程的帖子。
关于java - 如何将 jar 文件保存在外部但仍然在我的 Android 项目中使用它的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26487595/