Android 开发相关文章收集Android-gradleAndroid开发知识小集

浅谈build.gradle写法,促使我们更高效开发

2018-12-11  本文已影响503人  打酱油的日光灯

抓住人生中的一分一秒,胜过虚度中的一月一年!

背景

在开发中,build.gradle是必须配置的,本文章介绍一下build.gradle必须配置的代码,这些大家应该都会,主要是优化下写法

实现目标

1、多Module中minSdkVersion,targetSdkVersion,versionCode,versionName共用
2、v7包design包等依赖
3、签名文件模块配置
4、多渠道打包
5、64k方法数限制


1、多Module中minSdkVersion,targetSdkVersion,versionCode,versionName共用

当我们项目庞大时候,可能会依赖很多Module到项目中,这时每个Module都有自己的build.gradle,其中minSdkVersion等是必须配置的,当我们版本升级时候,需要每个Module都做修改,这样虽说也没多少操作,但也不是最高效的方法,所以我们便会想到怎样就可以一键可做修改

思路:将所有module中minSdkVersion等都引用我们指定的配置文件,这样改动一处即一键改动
1、首先在我们项目根build.gradle中配置

ext {
    compileSdkVersion = 27
    buildToolsVersion = '27.0.2'
    supportLibraryVersion = '27.1.1'

    minSdkVersion = 16
    targetSdkVersion = 27
    versionCode = 1
    versionName = "1.0.1"
}

2、在APP,Module中build.gradle中引用根配置的东西

compileSdkVersion rootProject.compileSdkVersion
    defaultConfig {
        applicationId "com.baoming"
        minSdkVersion rootProject.minSdkVersion
        targetSdkVersion rootProject.targetSdkVersion
        buildToolsVersion rootProject.buildToolsVersion
        versionCode rootProject.versionCode
        versionName rootProject.versionName

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        flavorDimensions "versionCode"
        multiDexEnabled true                    //添加多 dex分包支持

//        minifyEnabled true                      //是否混淆
//        zipAlignEnabled true                    //是否设置zip对齐优化
//        shrinkResources true                    // 移除无用的resource文件
    }
2、v7包design包等依赖

我们正常依赖写法

 implementation 'com.android.support:appcompat-v7:27.1.1'
 implementation 'com.android.support:design:27.1.1'

优化后写法

api "com.android.support:appcompat-v7:$rootProject.supportLibraryVersion"
api "com.android.support:design:$rootProject.supportLibraryVersion"
3、签名文件模块配置

通常我们签名文件jks别名密码都写到build.gradle中,如下

signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword "android"
            keyAlias "androiddebugkey"
            keyPassword "android"
        }
   }

优化后,我们别名密码等在build.gradle只写引用,值放到其他地方
1、在app同级新建文件夹signings,如图所示


app.png

2、将签名文件jks放到文件夹下
3、新建signing.properties,里边内容写别名,密码,jks路径等

KEYSTORE_FILEPATH=../signings/aijiayou.jks
STORE_PASSWORD=123456
KEY_ALIAS=aijiayou
KEY_PASSWORD=123456

4、build.gradle引用签名文件(写到最外层,和android{}同级)

Properties signingProperties = new Properties()
signingProperties.load(new FileInputStream(file("../signings/signing.properties")))

5、build.gradle配置签名文件

 signingConfigs {
        key {
            storeFile file(signingProperties['KEYSTORE_FILEPATH'])
            storePassword signingProperties['STORE_PASSWORD']
            keyAlias signingProperties['KEY_ALIAS']
            keyPassword signingProperties['KEY_PASSWORD']
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.key
        }
        debug {
            signingConfig signingConfigs.key
        }
    }
4、多渠道打包

多渠道打包我们经常会用到,同样也可以使用第三方工具进行分包
1、在AndroidManifest.xml中配置

 <meta-data
            android:name="UMENG_CHANNEL"
            android:value="${UMENG_CHANNEL_VALUE}" />

2、在build.gradle配置,前提是配置好签名文件,需要哪个渠道在productFlavors 添加即可

applicationVariants.all { variant ->
        variant.outputs.all { output ->

            def outputFile = output.outputFile
            if (outputFile != null && outputFile.name.endsWith('.apk')) {
                def fileName = outputFile.name.replace(".apk", "-${defaultConfig.versionName}.apk")
                outputFileName = fileName
            }
        }
    }
    productFlavors {
        aijiayuo {}
        yingyongbao {}
        xiaomi {}
        oppo {}
    }
    productFlavors.all {
        flavor -> flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name]
    }
5、64k方法数限制

大家我想可能会遇到这种问题,代码在低版本机跑步起来,可能是方法数超过了限制,错误信息
com.android.dex.DexIndexOverflowException:method IDnotin[0,0xffff]:65536
可采用这种办法
1、依赖multidex

compile 'com.android.support:multidex:1.0.3'

2、配置

defaultConfig {
        applicationId "com.aijiayou"
        minSdkVersion rootProject.minSdkVersion
        targetSdkVersion rootProject.targetSdkVersion
        buildToolsVersion rootProject.buildToolsVersion
        versionCode rootProject.versionCode
        versionName rootProject.versionName

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        flavorDimensions "versionCode"
---------------------------------------------------------------------------------------------------------
        multiDexEnabled true                    添加多 dex分包支持   (这条信息)
---------------------------------------------------------------------------------------------------------

//        minifyEnabled true                      //是否混淆
//        zipAlignEnabled true                    //是否设置zip对齐优化
//        shrinkResources true                    // 移除无用的resource文件
    }

3、MyApplication中重写

 @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        MultiDex.install(this);
    }

64K方法数限制简书

全部代码如下
apply plugin: 'com.android.application'

Properties signingProperties = new Properties()
signingProperties.load(new FileInputStream(file("../signings/signing.properties")))
android {

    compileSdkVersion rootProject.compileSdkVersion
    defaultConfig {
        applicationId "com.aijiayou"
        minSdkVersion rootProject.minSdkVersion
        targetSdkVersion rootProject.targetSdkVersion
        buildToolsVersion rootProject.buildToolsVersion
        versionCode rootProject.versionCode
        versionName rootProject.versionName

        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        flavorDimensions "versionCode"
        multiDexEnabled true                    //添加多 dex分包支持

//        minifyEnabled true                      //是否混淆
//        zipAlignEnabled true                    //是否设置zip对齐优化
//        shrinkResources true                    // 移除无用的resource文件
    }

    signingConfigs {
        key {
            storeFile file(signingProperties['KEYSTORE_FILEPATH'])
            storePassword signingProperties['STORE_PASSWORD']
            keyAlias signingProperties['KEY_ALIAS']
            keyPassword signingProperties['KEY_PASSWORD']
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.key
        }
        debug {
            signingConfig signingConfigs.key
        }
    }

    compileOptions {//使用JAVA8语法解析
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
       /* ndk {
            //设置支持的SO库架构(开发者可以根据需要,选择一个或多个平台的so)
            abiFilters "armeabi"
        }*/
    }
    applicationVariants.all { variant ->
        variant.outputs.all { output ->

            def outputFile = output.outputFile
            if (outputFile != null && outputFile.name.endsWith('.apk')) {
                def fileName = outputFile.name.replace(".apk", "-${defaultConfig.versionName}.apk")
                outputFileName = fileName
            }
        }
    }
    productFlavors {
        aijiayuo {}
        yingyongbao {}
        xiaomi {}
        oppo {}
    }
    productFlavors.all {
        flavor -> flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name]
    }
}

repositories {
    maven { url 'https://jitpack.io' }
    jcenter()
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    api "com.android.support:appcompat-v7:$rootProject.supportLibraryVersion"
    api "com.android.support:design:$rootProject.supportLibraryVersion"

    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    compile 'com.android.support:multidex:1.0.3'


}

最后,祝大家开发顺利!

上一篇下一篇

猜你喜欢

热点阅读