Android打包AAR,並輸出到指定目錄

在模塊化開發中,有時須要將獨立功能模塊打包輸出。android

注意:本例子在Android插件3.2.0上運行,在3.3+須要修改成Provider方式獲取variantgit

  • 編寫打包腳本,放在common.gradle文件中

// common.gradle

gradle.ext.dependencieInfo = []

/** * 獲取時間 yyyyMMdd * @return 時間字符串 */
static String releaseTime() {
    return new Date().format("yyyyMMdd", TimeZone.getDefault())
}

/** * 獲取時間 yyyyMMdd * @return 時間字符串 */
static String getFormatDate() {
    return new Date().format("yyyyMMdd_HHmmss", TimeZone.getDefault())
}

static def getGitHeadRefsSuffix() {
    try {
        // .git/HEAD描述當前目錄所指向的分支信息,內容示例:"ref: refs/heads/master\n"
        def headFile = new File('.git/HEAD')
        if (headFile.exists()) {
            String[] strings = headFile.getText('UTF-8').split(" ")
            if (strings.size() > 1) {
                String refFilePath = '.git/' + strings[1]
                // 根據HEAD讀取當前指向的hash值,路徑示例爲:".git/refs/heads/master"
                def refFile = new File(refFilePath.replace("\n", ""))
                // 索引文件內容爲hash值+"\n",
                // 示例:"90312cd9157587d11779ed7be776e3220050b308\n"
                return refFile.getText('UTF-8').substring(0, 7)
            }
        }
    } catch (Exception e) {
        e.printStackTrace()
    }
    return ""
}

// 打包aar
void packagingAAR(project, android) {
    android.libraryVariants.all { variant ->
        if (variant.buildType.name == "release") {
            // 修改aar名稱
            variant.outputs.all { output ->
                outputFileName = "${project.name}-V${android.defaultConfig.versionName}_${android.defaultConfig.versionCode}-${getGitHeadRefsSuffix}-${getFormatDate()}${isEmpty(variant.flavorName) ? "" : "-${variant.flavorName}"}-${variant.buildType.name}.aar"
            }
            // 複製aar到指定目錄
            variant.assemble.doLast {
                variant.outputs.all { output ->
                    // 輸出目錄在:項目目錄/build/outputs/aar/日期-gitCommit/
                    def outputPath = [project.rootDir.absolutePath, "build", "outputs", "aar", releaseTime() + "-" + getGitHeadRefsSuffix()].join(File.separator)
                    copy {
                        from output.outputFile
                        into outputPath
                    }
                    // 輸入依賴語句
                    gradle.dependencieInfo.add("api(name: '${output.outputFile.name.replace('.aar', '')}', ext: 'aar')")
                    println("${gradle.dependencieInfo.join("\n")}")
                }
            }
        }
    }
}
ext {
    // yyyyMMdd 時間
    releaseTime = this.&releaseTime
    // yyyyMMdd_HHmmss 時間
    getFormatDate = this.&getFormatDate
    // 獲取當前git commit點
    getGitHeadRefsSuffix = this.&getGitHeadRefsSuffix
    // 打包AAR
    packagingAAR = this.&packagingAAR
}

複製代碼
  • 在項目build.gradle引入common.gradle

引入common.gradle後,能夠在其餘模塊中使用common.gradle中的方法。api

// 根目錄build.gradle
apply from: "common.gradle"

buildscript {
    repositories {
        jcenter()
        mavenCentral()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        google()
    }
}

複製代碼

在lib模塊build.gradle使用bash

apply plugin: 'com.android.library'

android {
    compileSdkVersion rootProject.ext.android.compileSdkVersion

    defaultConfig {
        minSdkVersion rootProject.ext.android.lowMinSdkVersion
        targetSdkVersion rootProject.ext.android.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    packagingAAR(project, android)
}

dependencies {

}
複製代碼
  • 使用

在Terminal中使用命令打包輸出aar。app

gradlew :xxxa:assembleRelease :xxxb:assembleRelease
複製代碼
相關文章
相關標籤/搜索