使用Gradle生成包含所有依赖库(.jar或.aar)的aar包

杜辰龙
2023-12-01

Android Library项目中如果使用Android Gradle plugin打aar包,通过maven依赖的库,或者是local依赖的aar都不会包含在生成的aar包里,如果项目是发布一个SDK,为了方便开发者使用,我们倾向于生成一个包含所有依赖库以及.so等文件的aar包。

通过反复研究和测试,以下Gradle脚本能满足需求,如果需要对代码运行ProGuard混淆,则需要使用Gradle 2.1

方法是为项目增加一个sub project(如pkg_project)专门用于打包,该项目中build.gradle内容如下:

  1. apply plugin: 'java'
  2. version = 1.0
  3. buildscript {
  4. repositories {
  5. mavenCentral()
  6. }
  7. dependencies {
  8. classpath 'com.android.tools.build:gradle:19.1.0'
  9. }
  10. }
  11. repositories {
  12. mavenCentral()
  13. }
  14. dependencies {
  15. compile project(':<your_library_project>') //此处填写需要打包的Android Library Project name
  16. }
  17. task sync_jars() << {
  18. //把所有依赖的.jar库都拷贝到build/aar/libs下
  19. copy {
  20. into buildDir.getPath() +"/aar/libs"
  21. from configurations.compile.findAll {
  22. it.getName().endsWith(".jar")
  23. }
  24. }
  25. }
  26. task sync_aars(dependsOn:':<your_library_project>:assembleRelease') << {
  27. //把所有依赖的.aar库里包含的classes.jar都拷贝到build/aar/libs下,并重命名以不被覆盖
  28. def jar_name
  29. def aar_path
  30. def dest_dir = buildDir.getPath()+"/aar"
  31. configurations.compile.findAll {
  32. it.getName().endsWith(".aar")
  33. }.collect {
  34. aar_path = it.getPath()
  35. jar_name = "libs/"+it.getName().replace(".aar",".jar")
  36. copy {
  37. from zipTree(aar_path)
  38. into dest_dir
  39. include "**/*"
  40. rename 'classes.jar', jar_name
  41. }
  42. }
  43. }
  44. task fataar(dependsOn:[sync_aars, sync_jars]) << {
  45. task (obfuse_classes_jar, type: proguard.gradle.ProGuardTask) {
  46. //把build/aar/libs/*.jar混淆后生成build/aar/classes.jar
  47. configuration "proguard.cfg"
  48. injars buildDir.getPath()+"/aar/libs"
  49. outjars buildDir.getPath()+"/aar/classes.jar"
  50. libraryjars "${System.getProperty('java.home')}/lib/rt.jar"
  51. libraryjars "${System.getProperty('java.home')}/Contents/Classes/classes.jar"
  52. libraryjars System.getenv("ANDROID_HOME")+"/platforms/android-19/android.jar"
  53. }.execute()
  54. task (gen_aar, type: Zip) {
  55. //把生成最终的aar包,注意libs目录需要被排除
  56. def dest_dir = buildDir.getPath()+"/aar/"
  57. baseName = "mysdk-all"
  58. extension = "aar"
  59. destinationDir = file(buildDir.getPath())
  60. from dest_dir
  61. exclude "libs"
  62. }.execute()
  63. }

最后就可以使用gradlew pkg_project:fataar来打包了

 类似资料: