美文网首页
安卓开发:build.gradle配置

安卓开发:build.gradle配置

作者: LiuJP | 来源:发表于2019-01-11 14:59 被阅读12次

app/build.gradle

    apply plugin: 'com.android.application'

    def baseVername = '1.0.'
    def baseVercode = 1 //单款盒子去所属App properties中配置其相应版本号
    
    def baseBuildCnt = 1001
    def appSource
    def properties = new Properties()
    
    def outputMapFile = ''
    def outputApkFile = ''
    def appLable = ''
    def falsePkgName = ''
    
    def defaultChannelName = "hole"
    
    def defaultChannels = [0]   //缺省只出BOX1渠道包即可
    
    def getVersionName = { ->
        //根据gitlab中的提交纪录次数,作为编译版本名字
        try {
            def stdout = new ByteArrayOutputStream()
            exec {
                commandLine 'git', 'rev-list', 'HEAD', '--count'
                standardOutput = stdout
            }
            def new_baseVername = properties.getProperty("baseVername")
            if (new_baseVername != null) {
                baseVername = new_baseVername
            }
            def new_baseBuildCnt = properties.getProperty("baseBuildCnt")
            if (new_baseBuildCnt != null) {
                baseBuildCnt = Integer.parseInt(new_baseBuildCnt)
            }
            println('盒子模板App加载配置:baseVername  -- ' + baseVername)
            return baseVername + (Integer.parseInt(stdout.toString().trim()) + baseBuildCnt)
        } catch (ignored) {
            def versionName = properties.getProperty("appVerName")
            println('盒子模板App加载配置:versionName  -- ' + versionName)
            return versionName
        }
    }
    
    
    
    def getVersionCode = { ->
        //根据gitlab中tag标签数,作为版本代码
        try {
            if (defaultVersionCode > 0) {
                return defaultVersionCode
            }
            def code = new ByteArrayOutputStream()
            exec {
                commandLine 'git', 'tag', '--list'
                standardOutput = code
            }
            return code.toString().trim().split("\n").size() + baseVercode
        } catch (ignored) {
            def versionCode = properties.getProperty("appVerCode")
            println('盒子模板App加载配置:baseVercode  -- ' + versionCode)
            return versionCode
        }
    }
    
    
    
    
    def loadLocalProperties = { ->
        println(' ****************** AppTemplateBox脚本执行 ******************')
        if (project.properties.containsKey("game") && null != project.properties.get("game")) {
            File configFile = new File(projectDir, 'properties/app-' + project.properties.get("game") + '.properties');
            if (configFile.exists()) {
                properties.load(configFile.newDataInputStream())
                println('盒子模板App加载配置:命令行指定配置文件,' + configFile.getName())
            } else {
                println('盒子模板App加载配置:未定义')
            }
        } else {
            //加载配置文件
            File appSetting = new File(projectDir, 'local.properties');
            if (appSetting.exists()) {
                println(appSetting.absolutePath)
                properties.load(appSetting.newDataInputStream())
                if (properties.getProperty('config') == null)
                    appSetting = null
                else {
                    properties.load(new File(projectDir, properties.getProperty('config')).newDataInputStream())
                    println('盒子模板App加载配置:使用本地定义(local.properties),' + properties.get("config"))
                }
            }
            if (appSetting == null || !appSetting.exists()) {
                properties.load(new File(projectDir, 'app-hole.properties').newDataInputStream())
                println('盒子模板App加载配置:未定义,使用缺省配置, ')
            }
        }
    
        appLable = new String(properties.getProperty("appLable").getBytes("iso-8859-1"), "utf-8");
    
        def channel = new String(properties.getProperty("defaultChannelName").getBytes("iso-8859-1"), "utf-8");
    
        if (channel != null) {
            defaultChannelName = channel
        }
    
    
        outputApkFile = properties.getProperty("applicationId") + "-v" + getVersionCode() + "-" + getVersionName() + "_"
    
        // def temp = properties.getProperty("applicationId") + "-v" + getVersionCode()+"-"+getVersionName()+".apk"
        outputMapFile = outputApkFile.replace(".apk", "-map.txt")
    
        println('盒子模板App加载配置: --- outputApkFile --- ' + outputApkFile + "\t; outputMapFile:" + outputMapFile)
    }
    
    
    android {
        compileSdkVersion rootProject.ext.android.compileSdkVersion
        buildToolsVersion rootProject.ext.android.buildToolsVersion
    
        loadLocalProperties()
    
        lintOptions {
            abortOnError = false
        }
    
    /*    signingConfigs {
            sign {
                keyAlias 'iplay'
                keyPassword 'passwd11'
                storeFile file('../keystore_box_pay.jks')
                storePassword 'passwd11'
            }
        }*/
    
        applicationVariants.all {
            def buildType = it.buildType.name
            it.outputs.all {
                if (buildType == "release") {
                    if (it.outputFile.name.endsWith("-release.apk")) {
                        it.getPackageApplication().outputDirectory = new File(project.rootDir.absolutePath + "/release")
                    }
                }
                def apkName = "${applicationId}-${getVersionName}-${buildType}" + defaultChannels[0] + ".apk"
                it.outputFileName = apkName
            }
        }
    
        signingConfigs {
            sign {
                keyAlias = 'Redbull'
                keyPassword = 'Redbull123$%^'
                storeFile = file('../keystore.jks')
                storePassword = 'Redbull123$%^'
            }
        }
    
    
        defaultConfig {
            // println(" --> 当前编译应用输出版本名称为:" + getVersionName())
            minSdkVersion rootProject.ext.android.minSdkVersion
            targetSdkVersion rootProject.ext.android.targetSdkVersion
    
            applicationId properties.getProperty("applicationId")
            versionCode 100102
            versionName getVersionName()
    
            println(" --> 当前编译应用输出包名为:" + applicationId)
            println(" --> 当前编译应用输出版本号为:" + getVersionCode())
            println(" --> 当前编译应用输出版本名称为:" + getVersionName())
    
    
    
            def auth = properties.getProperty("ProviderPrefix")
            appSource = properties.getProperty("appSource")
    
    
            buildConfigField("String", "HostAppPkgName", ('"' + properties.getProperty("HostAppPkgName") + '"'))
            buildConfigField("String", "PluginCenterName", ('"' + properties.getProperty("PluginCenterName") + '"'))
            buildConfigField("String", "PluginName", ('"' + properties.getProperty("PluginName") + '"'))
            buildConfigField("String", "AdPluginName", ('"' + properties.getProperty("AdPluginName") + '"'))
            buildConfigField("String", "gameObbMd5", ('"' + properties.getProperty("gameObbMd5") + '"'))
            buildConfigField("boolean", "gameIsNeedObb", properties.getProperty("gameIsNeedObb"))
    
            buildConfigField("String", "PayPluginName", ('"' + properties.getProperty("PayPluginName") + '"'))
            def modesc = new String(properties.getProperty("modDesc").getBytes("iso-8859-1"), "utf-8");
            buildConfigField("String", "modDesc", ('"' + modesc + '"'))
    
    
    
            buildConfigField("String", "AdPkgName", ('"' + properties.getProperty("AdPkgName") + '"'))
            buildConfigField("String", "AdgdtAid", ('"' + properties.getProperty("AdgdtAid") + '"'))
            buildConfigField("String", "AdgdtPid", ('"' + properties.getProperty("AdgdtPid") + '"'))
    
    
    
            buildConfigField("String", "appLable", ('"' + appLable + '"'))
            buildConfigField("String", "applicationId", ('"' + properties.getProperty("applicationId") + '"'))
            //打点
            buildConfigField("String", "talkingDataId", ('"' + properties.getProperty("talkingDataId") + '"'))
            buildConfigField("String", "tracker_id", ('"' + properties.getProperty("tracker_id") + '"'))
    
    
            if (properties.getProperty("falsePkgName")) {
                falsePkgName = properties.getProperty("falsePkgName")
            } else {
                falsePkgName = properties.getProperty("applicationId")
            }
            //真实包名
            buildConfigField("String", "falsePkgName", ('"' + falsePkgName + '"'))
    
            //沙盒认证
            buildConfigField("String", "ProviderPrefix", ('"' + auth + '"'))
            buildConfigField("String", "channel", ('"' + defaultChannelName + defaultChannels[0] + '"'))
    
            manifestPlaceholders = [
                    appLable             : appLable,
                    ApplicationId        : properties.getProperty("applicationId"),
    
                    SANDBOX_AUTHORITIES  : auth,
                    SANDBOX_AUTHORITIES_0: auth + "0",
                    SANDBOX_AUTHORITIES_1: auth + "1",
                    SANDBOX_AUTHORITIES_2: auth + "2",
                    SANDBOX_AUTHORITIES_3: auth + "3",
                    SANDBOX_AUTHORITIES_4: auth + "4",
                    SANDBOX_AUTHORITIES_5: auth + "5",
                    SANDBOX_AUTHORITIES_6: auth + "6",
                    SANDBOX_AUTHORITIES_7: auth + "7",
                    SANDBOX_AUTHORITIES_8: auth + "8",
                    SANDBOX_AUTHORITIES_9: auth + "9",
            ]
    
            ndk {
                abiFilter "armeabi"
            }
        }
    
    
    
        sourceSets {
            def appSourcePath = appSource.toString().split(",")
            appSourcePath.each { sourceItem ->
                main.assets.srcDirs += ['src/' + sourceItem + '/assets']
                main.res.srcDirs += ['src/' + sourceItem + '/res']
                main.java.srcDirs += ['src/' + sourceItem + '/java']
            }
        }
    
    
    
    
        buildTypes {
            release {
                multiDexEnabled false
                minifyEnabled true
                proguardFiles 'proguard-rules.pro'
    
                rootProject.ext.allProguards.each { name ->
                    proguardFiles.add(name)
                    println(' --> 编译使用混淆文件:' + name)
                }
    
    //            移除无用的resource文件
                shrinkResources true
                signingConfig = signingConfigs.sign
            }
    
            debug {
                signingConfig = signingConfigs.sign
                multiDexEnabled false
            }
    
        }
    
    
        flavorDimensions "default"
        productFlavors {
            def flavers = [:]
            def channelTimes = defaultChannels.size()
            channelTimes.times { n ->
                def thisChannelNum = defaultChannels[n]
                def thisChannelName = defaultChannelName + thisChannelNum
                //  println('thisChannelName 多渠道: '+thisChannelName)
                flavers[n] = "$thisChannelName" {
                    buildConfigField "String", "CHANNEL", ('"' + thisChannelName + '"')
                }
            }
        }
    }
    
    
    
    
    
    
    task buildMyListFile {
        // group 'build'
        dependsOn 'assembleRelease'
        doLast {
            println("=====================buildMyListFile.doLast begin .=========================")
            def intoFile = project.rootDir.getAbsolutePath() + "/release/"
            def fromFile = project.buildDir.getAbsolutePath() + "/outputs/apk/"
    
            def files = file(fromFile).listFiles().sort()
            files.each { File file ->
                if (file.isDirectory()) {
                    println " *** $file.name ***"
                    def temDir = fromFile + file.name + "/release"
                    //  println("============"+temDir)
                    def tem_file = new File(temDir)
                    if (tem_file.exists()) {
                        def files_1 = tem_file.listFiles().sort()
                        files_1.each { File files_2 ->
                            if (files_2.getName().startsWith("apk-")) {
                                //  println " *** $files_2.name ***"
                                copy {
                                    from files_2
                                    into intoFile
                                }
                            }
                        }
                    }
                }
            }
            println("=====================buildMyListFile.doLast success.=========================")
        }
    }
    
    
    
    
    task buildCompressed {
        dependsOn 'buildMyListFile'
        doLast {
            println("=====================buildCompressed.doLast begin .=========================")
            println(' ********************************** ' + System.getProperties().get("os.name") + '*********************')
            println(' --> 打包已完成,开始后续工作 ...')
    
            def fromFile = project.rootDir.getAbsolutePath() + "/release/"
            def files = file(fromFile).listFiles().sort()
            files.each { File file ->
                println " *** $file.name ***"
                if (file.getName().endsWith(".apk")) {
                    def newOutputApkFile = file.getName()
    
                    println("=====================build.buildCompressed " + newOutputApkFile + "=========================")
    
                    task(newOutputApkFile) {
                        def guardJarFile = new File(project.rootDir, 'AndResGuard/AndResGuard-cli-1.2.0.jar')
                        //AndResGuard jar包
                        def guardConfigFile = new File(project.rootDir, 'AndResGuard/config.xml')
                        //config.xml配置文件
                        def originApkFile = new File(project.rootDir, "release/" + newOutputApkFile)
                        //需要压缩的apk
                        def outputDir = new File(project.rootDir, "release/compressed/") //输出的位置
    
                        def zipalign = new File(project.rootDir, 'AndResGuard/zipalign')
                        //AndResGuard jar包
                        if (System.getProperties().get("os.name").startsWith('Mac')) {
                            zipalign = new File(project.rootDir, 'AndResGuard/zipalign.cmd')
                            //AndResGuard jar包
                            println "    --> 资源压缩:使用mac版本zipalign," + zipalign
                        }
    
                        def chmod = """chmod 755 ${zipalign}""".execute()
                        chmod.waitFor()
    
                        println("  --> java -jar ${guardJarFile} ${originApkFile} -config ${guardConfigFile} -out ${outputDir}  -zipalign ${zipalign}")
                        if (originApkFile.exists()) {
                            def proc = """java -jar ${guardJarFile} ${originApkFile} -config ${
                                guardConfigFile
                            } -out ${outputDir} -zipalign ${zipalign}""".execute()
                            proc.waitFor();
                            if (outputDir.exists()) {
                                outputDir.eachFile {
                                    if (it.getName().endsWith("_signed_aligned.apk")) {
                                        println "    --> 资源压缩:保留结果文件 " + it.getName() + " :" + it.length()
                                        it.renameTo(new File(project.rootDir, "release/" + newOutputApkFile.replace(".apk", "-compressed.apk")))
                                    } else if (it.getName().startsWith("resource_mapping") && it.getName().endsWith(".txt")) {
                                        println "    --> 资源压缩:保留混淆映射文件 " + it.getName() + " :" + it.length()
                                        it.renameTo(new File(project.rootDir, "release/" + outputMapFile.replace(".txt", ".rsc.txt")))
                                    } else if (it.isDirectory()) {
                                        println "    --> 资源压缩:删除多余目录 " + it.getName()
                                        it.deleteDir()
                                    } else {
                                        println "    --> 资源压缩:删除多余文件 " + it.getName() + " :" + it.length()
                                        it.delete()
                                    }
                                }
                            }
                            if (proc.exitValue() != 0) {
                                println "    --> 资源压缩:失败,错误日志:\n${proc.err.text}"
                            }
                        } else {
                            println "    --> 资源压缩:失败,缺少原始APK文件"
                        }
    
    
                        File originalInput = new File(project.rootDir, "release/" + newOutputApkFile.replace(".apk", "-compressed.apk"))
                        File workDir = originalInput.getParentFile()
                        File releaseDir = new File(workDir, "release")
                        if (releaseDir.exists()) {
                            releaseDir.deleteDir()
                        }
    
                        /*                project.exec {
                                            executable = 'java'
                                            args += '-jar'
                                            args += new File(project.projectDir, '../channelrepacker.jar').getAbsolutePath()
                                            args += "-source=" + originalInput.getAbsolutePath()
                                            args += '-key=' + new File(project.projectDir, '../keystore_box_pay.jks').getAbsolutePath()
                                            args += '-keyPasswd=passwd11'
                                            args += '-keyAlias=passwd11'
                                            println("::" + args)
                                        }
                    */
    
                        project.exec {
                            executable = 'java'
                            args += '-jar'
                            args += new File(project.projectDir, '../channelrepacker.jar').getAbsolutePath()
                            args += "-source=" + originalInput.getAbsolutePath()
                            args += '-key=' + new File(project.projectDir, '../keystore.jks').getAbsolutePath()
                            args += '-keyPasswd=Redbull123$%^'
                            args += '-channel=' + thisChannelName
                            args += '-keyAlias=Redbull'
                            println("::" + args)
                        }
                    }
                }
            }
            println("=====================buildCompressed.doLast success.=========================")
        }
    }
    
    
    
    
    
    
    
    
    repositories {
        flatDir {
            dirs 'libs'
        }
        mavenCentral()
        google()
    }
    
    
    
    
    
    
    
    dependencies {
    //    compile files('libs/UM_SDK-1.1.2.0.jar')
        api files('libs/javabase64-1.3.1.jar')
        api files('libs/pluginInterface.jar')  //不能删除这个jar,否则起不来
        api files('libs/TalkingData_Analytics_Android_SDK_V2.2.48.jar')  //打点的jar包
        api 'b.c.a:YYhhSafconn:1.0.4'
    
        api(name: 'open_ad_sdk', ext: 'aar')
        api files('libs/android-query-full.0.26.7.jar')
    
        //定义在config.gradle数组中,基于项目名称配置的所有dependencies,方便导入
        if (rootProject.ext.deps.containsKey(project.name)) {
            rootProject.ext.deps[project.name].split(',').each { dep ->
                println('    --> ' + project.name + '定义的依赖库:' + rootProject.ext.dependencies[dep])
                api(rootProject.ext.dependencies[dep]) {
                    /*         if (rootProject.ext.excludeModule[dep] != null) {
                                 exclude module: rootProject.ext.excludeModule[dep]
                                 println('    --> ' + project.name + '<移除>特定依赖库:' + rootProject.ext.excludeModule[dep])
                             }
                             if (rootProject.ext.excludeGroup[dep] != null) {
                                 exclude group: rootProject.ext.excludeGroup[dep]
                                 println('    --> ' + project.name + '<移除>特定依赖组:' + rootProject.ext.excludeGroup[dep])
                             }*/
                }
            }
        }
    }

build.gradle 依赖库配置

allprojects {
    repositories {
        jcenter()
        mavenCentral()
        maven {
            url "http://10.0.0.242:8081/artifactory/libs-release-local"
            credentials {
                username = "yyhd-repo"
                password = "JkJheIGh28Kha0jqwUYT"
            }
        }
    }
}

相关文章

网友评论

      本文标题:安卓开发:build.gradle配置

      本文链接:https://www.haomeiwen.com/subject/jiexdqtx.html