把依赖库打包进JAR中的方法

引入

在自己为Android APP编写需要的Java library的时候,往往会在library中依赖第三方的库,举个例子:
做了一个账号管理的library,其中由于需要使用http连接,所以library工程中有以下依赖

implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.okhttp3:okhttp:3.9.1'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'commons-validator:commons-validator:1.6'
implementation 'io.reactivex.rxjava2:rxjava:2.1.10'

在功能开发完成,编译成class文件以后,如果只是使用jar来打包我们自己source file生成的class文件

jar cvf sample.jar -C sample_lib/build/intermediates/classes/release

问题

当把这样生成JAR file放入APP工程后,由于JAR中没有对应的依赖,会有以下问题:

  1. 在APP中使用时需要把JAR工程中的依赖在APP中再写一次;
  2. 实测哪怕添加上了依赖,compile可以过以后,在运行时会出现找不到类的runtime error;

那么在生成JAR包时,把对应library的依赖也一同打包进JAR是比较好的解法。

解决方案 - 使用IDEA

使用Android Studio没有找到现成的方法,目前对gradle也不够熟悉,没法自己动手通过编写gradle task来解决问题。
那么使用IDEABuild Artifacts就成为一个很好的方法。

步骤

初始的时候,Build -> Build Artifacts是灰色的。

disabled-build-artifacts.jpg

此时需要在File -> Project Structure中进行设置:
setting.jpg

create_JAR_from_module.jpg

不太清楚extract to the target JARcopy to the output diretory and link via manifest的区别,就直接采用默认的第一项,后续再来study差异。
继续设置要要生成的JAR的名字后,选择好要把哪一个module来打包JAR。
jar_name_and_module_select.jpg

设置完成后,Build -> Build Artifacts就已经可用了
build_artifacts_enabled.jpg

直接通过这个菜单进行JAR生成,然后在之前设置好的目录下(设置JAR包名的步骤中)去找对应的JAR就可以用了。

你可能感兴趣的:(把依赖库打包进JAR中的方法)