In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces the relevant knowledge of how to configure build.gradle in Android, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this Android article on how to configure build.gradle. Let's take a look at it.
1. Build.gradle file of Project:
The corresponding build.gradle code is as follows:
/ / Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript {/ / here are the dependencies needed for gradle script execution, respectively, the corresponding maven library and plug-in repositories {google () / / add google () configuration from Android Studio3.0. You can reference the open source project jcenter () on google / / is a code hosting repository similar to github, and declares the jcenter () configuration. You can easily reference the open source project on jcenter} dependencies {classpath 'com.android.tools.build:gradle:3.0.0'//// here is the plug-in for android gradle,gradle is a powerful project building tool / / NOTE: Do not place your application dependencies here They belong / / in the individual module build.gradle files}} allprojects {/ / here are the dependencies needed by the project itself, such as the maven library repositories {google () jcenter ()}} / / when running gradle clean, execute the task task defined here. / / this task inherits from Delete and deletes the build directory in the root directory. / / is equivalent to executing Delete.delete (rootProject.buildDir). / / gradle uses the groovy language, and you don't have to add () when calling method. Task clean (type: Delete) {delete rootProject.buildDir}
The buildscript {} closure is the dependency for gradle script execution, which is the corresponding maven library and plug-in, respectively.
Allprojects {} closures are dependencies needed by the project itself, such as the maven libraries required by the project.
Task clean (type: Delete) {} executes the task task defined here when running gradle clean, which inherits from Delete and deletes the build directory in the root directory. Buildscript contains repositories closure and dependencies closure.
Repositories {} closure: configuring remote repositories
The closure declares the configuration of jcenter () and google (), where jcenter is a code hosting repository that hosts many Android open source projects. After jcenter is configured here, we can easily reference open source projects on jcenter. After Android Studio3.0, we have added google () configuration and can reference open source projects on google.
Dependencies {} closures: configure the build tool
The closure declares a Gradle plug-in using classpath, and since Gradle is not just used to build the Android project, the relevant plug-ins are introduced here to build the Android project, where '3.3.3' is the version number of the plug-in, which can be adjusted according to the latest version number.
2. Build.gradle file of Module:
As can be seen from the contents of the file, it is mainly divided into three parts, as shown in the following figure:
1 、 apply plugin:
/ / declare to be an Android program, / / com.android.application indicates that this is an application module / / com.android.library identifies that this is a library module / / and the difference: the former can be run directly, followed by apply plugin: 'com.android.application' depending on another application
The first line in the file uses apply plugin to indicate that a plug-in is applied, and the plug-in generally has two values to choose from:
'com.android.application', indicates that the module is an application module, which can be run directly, and the package is an .apk file.
'com.android.library', indicates that the module is a library module and can only be run as a code base attached to other application modules. The packaged module is a .aar file.
2. Android {} closure:
The main purpose of this closure is to configure the various properties built by the project:
2.1.Add signingConfigs {} closures:
SigningConfigs {/ / automatic packaging configuration release {/ / online environment keyAlias' test' keyPassword '123456' storeFile file (' test.keystore') storePassword '123456'} debug {/ / development environment keyAlias' test' keyPassword '123456' storeFile file (' test.keystore') storePassword '123456'}}
You can add the signature configuration manually, or select app through Project Structure, and click Singing to add it, as shown in the following figure:
Configure Singing.png
After the signature configuration is completed, it is convenient to package with signatures. There are two Type in the Build Variants of module, debug and release. You can choose any type to package, and they will use their respective configured Key for packaging. Execute Run app or Build- > Build apk to automatically generate Apk files under the module name/app/build/outputs/apk path. Another packaging method is Build- > Generate Signed APK to generate Apk by filling in the signature information.
2.2.2.The compileSdkVersion: sets the Android version to be used when compiling
2.3.The buildToolsVersion: set the version of the build tool used during compilation, and remove this configuration after Android Studio3.0
2.4.The defaultConfig {} closure:
The Android version defaultConfig {applicationId "com.billy.myapplication" / / the package name of the project minSdkVersion 16 com.billy.myapplication / the minimum compatible version of the project targetSdkVersion 27 / the target version of the project versionCode 1 / version number versionName "1.0" / / the version name testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" / / indicates that you want to use AndroidJUnitRunner for unit testing}
ApplicationId: specifies the package name of the project.
MinSdkVersion: specifies the minimum compatible version of the project. If the device is smaller than this version or greater than maxSdkVersion (generally not used), this application cannot be installed. 16 is specified here, which means minimum compatibility to Android 4.1system.
TargetSdkVersion: specify the target version of the project, indicating that it has been fully tested on the target version, and the system will start some latest features of the target system and the behavior changes of the Android system platform for the application. It will take effect only if the property value of targetSdkVersion is set to greater than or equal to the API version of the system platform. For example, if you specify a target targetSdkVersion version value of 22, it means that the program has only been fully tested on the Android5.1 version at most, and new features such as system runtime permissions on Android6.0 systems (corresponding to Sdk 23) will not be enabled.
VersionCode: indicates the version number. Generally, this value can only be increased when it is packaged and launched, and cannot be seen after packaging.
VersionName: represents the name of the version and is displayed in the application market.
The testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" indicates that you want to use AndroidJUnitRunner for unit testing.
2.5. BuildTypes {} closure:
This closure mainly specifies the main configuration for generating installation files, and generally contains two child closures, one is debug closure, which is used to specify the configuration for generating beta installation files, which can be ignored and left unwritten, and the other is release closure, which is used to specify the configuration for generating official installation files. The parameters that can be configured are the same, but the biggest difference is that the default attribute configuration is different. The attribute configuration supported by the two modes is shown below:
BuildTypes configuration .png
BuildTypes {/ / production / test environment configuration release {/ / production environment buildConfigField ("boolean", "LOG_DEBUG", "false") / / configure Log log buildConfigField ("String", "URL_PERFIX", "\" https://release.cn/\"")// configure whether the URL prefix minifyEnabled false// confuses proguardFiles getDefaultProguardFile ('proguard-android.txt')) 'proguard-rules.pro'// specifies the obfuscated rule file signingConfig signingConfigs.release// sets whether the signature information pseudoLocalesEnabled false// generates a pseudo-locale in APK To help with internationalization, not much zipAlignEnabled true// is used to optimize the ZIP alignment of APK packages to reduce the size of zip and increase operational efficiency. ApplicationIdSuffix 'test'// adds a suffix in applicationId, and not much versionNameSuffix' test'// adds a suffix in applicationId. Rarely used} debug {/ / Test environment buildConfigField ("boolean", "LOG_DEBUG", "true") / / configure Log log buildConfigField ("String", "URL_PERFIX", "\" https://test.com/\"")// configure whether the URL prefix minifyEnabled false// confuses proguardFiles getDefaultProguardFile ('proguard-android.txt')) 'proguard-rules.pro'// specifies the confusing rule file signingConfig signingConfigs.debug// setting signature information whether debuggable false// supports breakpoint debugging jniDebuggable false// can debug NDK code whether renderscriptDebuggable false// turns on rendering scripts that are some c-written rendering methods zipAlignEnabled true// performs ZIP alignment optimization on APK packages Reduce the size of zip, increase operational efficiency whether pseudoLocalesEnabled false// generates pseudo-language environment in APK to help internationalize things, generally used less applicationIdSuffix 'test'// adds a suffix in applicationId, less commonly used versionNameSuffix' test'// adds a suffix in applicationId, generally used not much}}
Release {} closure and debug {} closure can be configured with the same parameters, but the biggest difference is that the default attribute configuration is different:
MinifyEnabled: indicates whether to obfuscate the code, true means to obfuscate the code, false indicates that the code is not confused, and the default is false.
ProguardFiles: specifies the obfuscation rule file. Here, two files, proguard-android.txt file and proguard-rules.pro file, are specified. Proguard-android.txt file is the default obfuscation file, which defines some general obfuscation rules. The proguard-rules.pro file is located in the root directory of the current project, where you can define some project-specific obfuscation rules.
BuildConfigField: used to solve the Beta version service and Release version service address is different or some Log printing requirements control. For example: configure buildConfigField ("boolean", "LOG_DEBUG", "true"), this method takes three non-empty parameters, the first: determine the type of the value, the second: specify the name of the key, and the third: pass the value, and the BuildConfig.LOG_DEBUG can be called when called.
Debuggable: indicates whether breakpoint debugging is supported. Release defaults to false and debug defaults to true.
JniDebuggable: indicates whether NDK code can be debugged. Use lldb to debug c and C++ code. Release defaults to false.
SigningConfig: set the signature information and configure the corresponding signature through signingConfigs.release or signingConfigs.debug. However, before adding this configuration, you must add a signingConfigs closure and add the corresponding signature information.
RenderscriptDebuggable: whether to enable the rendering script is some of the rendering methods written by c, and the default is false.
RenderscriptOptimLevel: represents the rendering level. The default is 3.
PseudoLocalesEnabled: not much is used to generate pseudo-locales in APK to help internationalize things.
ApplicationIdSuffix: it is the same as the configuration in defaultConfig. Here, a suffix is added to applicationId, which is not commonly used.
VersionNameSuffix: means to add a suffix to the version name, which is not commonly used.
ZipAlignEnabled: indicates whether to perform ZIP alignment optimization on the APK package to reduce the zip size and increase the running efficiency. Both release and debug are true by default.
2.6. sourceSets {} closure: configure the directory to point to
SourceSets {/ / directory points to configuration main {jniLibs.srcDirs = ['libs'] / / specify lib library directory}}
Configure jniLibs.srcDirs = ['libs'] to generate a jniLibs folder under the Android view of Android studio, which makes it convenient for us to store jar packages and library files, where the jniLibs under the Android view and the libs under the project view point to the same folder (app → libs), as shown below:
2.7. packagingOptions {} closures: related configurations when packaging
As more and more third-party libraries are relied on in the project, it is possible that the same (name) file exists in both dependent libraries. If so, Gradle will prompt an error (warning) when packing. Then you can follow the prompts and then use the following methods to remove duplicate files, more commonly using exclude to remove duplicate files, for example:
PackagingOptions {/ / pickFirsts is used for packaging errors when there are duplicate files. This configuration will use the first matching file to be packaged into apk / / indicating that when there are duplicate META-INF files in the apk, there are duplicate LICENSE files in the directory. Only the first one is used so that the package will not report errors pickFirsts = ['META-INF/LICENSE'] / / merges. Why merge duplicate files when duplicate files occur? The file is then packaged into apk / / there is a default value merges = [] this will remove the default value, so we add merge 'META-INF/LICENSE' / / after the default value in the following way, using butterknife, A process done by dagger2. By the same token, if you encounter a similar problem, just follow the hint of gradle and do similar treatment. Exclude 'META-INF/services/javax.annotation.processing.Processor'}
ProductFlavors {} closure: multiple channel configurations
This configuration is often used, usually when adapting to multiple channels, you need to do some special processing for specific channels, such as setting different package names, application names, and so on. Scenario: when we use YouMeng statistics, we usually need to set a channel ID, so we can use productFlavors to generate packages corresponding to channel information, such as:
The use of android {productFlavors {wandoujia {/ / pea pod channel package configuration manifestPlaceholders = [UMENG_CHANNEL_VALUE: "wandoujia"] / / manifestPlaceholders is introduced in the following section (placeholder in AndroidManifest)} xiaomi {manifestPlaceholders = [UMENG_CHANNEL_VALUE: "xiaomi"] applicationId "com.wiky.gradle.xiaomi" / / configuration package name} _ manifestPlaceholders = [UMENG_CHANNEL_VALUE: "_ 360"]} / /.}
Of course, there are more concise ways:
Android {productFlavors {wandoujia {} xiaomi {} _ 360 {} /...} productFlavors.all {/ / batch modification, similar to a sequential traversal flavor-> flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name]}}
After configuration, type gradlew assembleRelease (windows) in the command line window (Terminal) to start packaging, and the corresponding instruction in the Mac system should be. / gradlew assembleRelease. Of course, if you want the debug version of the package, just change the assembleRelease in the instruction to assembleDebug. The final generated package is still in app/build/outputs/apk. The default naming format is app-wandoujia-release-unsigned.apk, and the appropriate channel can be selected in the Build Variants of module.
Note: Android Studio3.0 needs to be in the build.gradle of the main app
DefaultConfig {targetSdkVersion:***minSdkVersion: * versionCode:***versionName: * / / add a sentence after the version name, which means that the dimension of flavor dimension is the version number, so that the dimensions are all unified. FlavorDimensions "versionCode"}
2.9. lintOptions {} closure: code scan analysis
Lint is a code scan analysis tool provided by Android Studio, which can help us find code structure / quality problems and provide some solutions, and this process does not require our handwritten test cases.
Each problem found by Lint has a description and level (similar to the bug found by the test), and we can easily locate the problem and solve it according to its severity.
/ / the program checks lint when compiling, and any error prompts it to stop build. We can turn off the switch lintOptions {abortOnError false / / does not stop packaging checkReleaseBuilds false / / when packaging release versions even if an error is reported.}
3. Dependencies {} closure:
The closure defines the dependencies of a project, which generally have three types of dependencies: local dependency, library dependency, and remote dependency. Local dependencies can add dependencies to local jar packages or directories, library dependencies can add dependencies to library modules in a project, and remote dependencies can add dependencies to open source projects on jcener libraries. The compile imported library from Android Studio3.0 is not in use, but is completely equivalent to the previous compile through api and implementation,api. The library introduced with api can be used throughout the project. Only the corresponding Module can be used for the library introduced with implementation, and other Module cannot be used. As the previous project uses compile dependency, the situation is that the module coupling is too high, which is not conducive to the disassembly of the project. After using implementation, it is more complex to use, but it can reduce the coincidence and improve the security.
Dependencies {/ / Project dependency implementation fileTree (include: ['* .jar'] Dir: 'libs') / / Local jar package relies on implementation' com.android.support:appcompat-v7:27.1.1'// remote dependency on implementation 'com.android.support.constraint:constraint-layout:1.1.2' testImplementation' junit:junit:4.12'// declaration test case library androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation' com.android.support.test.espresso:espresso-core:3.0.2'}
Implementation fileTree (include: ['* .jar'], dir: 'libs'): implementation fileTree is a local dependency declaration that adds all files with the .jar suffix in the libs directory to the build path of the project.
The implementation 'com.android.support:appcompat-v7:27.1.1':implementation statement is a remote dependency declaration,' com.android.support:appcompat-v7:27.1.1' is a standard remote dependency library format, where com.android.support is the domain name part, which is used to distinguish the libraries of different companies, and appcompat-v7 is the component name, which is used to distinguish different libraries of the same company 27.1.1 is the version number, which is used to distinguish different versions of the same library. After adding this statement, Gradle will first check whether the library has been cached locally when building the project. If there is no cache, it will automatically download it online, and then automatically add it to the build path of the project.
TestImplementation and androidTestImplementation: denote a declared test case library.
The complete build.gradle configuration for Module is as follows:
/ / declare to be an Android program, / / com.android.application indicates that this is an application module / / com.android.library identifies that this is a library module / / and the difference: the former can be run directly The next step is to run apply plugin depending on another application: 'com.android.application'android {signingConfigs {/ / automatic packaging configuration release {/ / online environment keyAlias' test' keyPassword '123456' storeFile file (' test.jks') storePassword '123456'} debug {/ / development environment keyAlias' test' keyPassword '123456' storeFile file (' test.jks') storePassword '123456'} compileSdkVersion 27move / setup The Android version defaultConfig {applicationId "com.billy.myapplication" / / the package name of the project {minSdkVersion 16 com.billy.myapplication / the minimum compatible version of the project targetSdkVersion 27 / the target version of the project versionCode 1 stop / version number versionName "1.0" / / version name flavorDimensions "versionCode" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" / / indicates that you want to use AndroidJUnitRunner for unit testing} buildTypes {/ / production / test environment configuration Set release {/ / production environment buildConfigField ("boolean") "LOG_DEBUG", "false") / / configure Log log buildConfigField ("String", "URL_PERFIX", "\" https://release.cn/\"")// configure whether the URL prefix minifyEnabled false// confuses proguardFiles getDefaultProguardFile ('proguard-android.txt')) 'proguard-rules.pro'// specifies the obfuscated rule file signingConfig signingConfigs.release// sets whether the signature information pseudoLocalesEnabled false// generates a pseudo-locale in APK To help with internationalization, not much zipAlignEnabled true// is used to optimize the ZIP alignment of APK packages to reduce the size of zip and increase operational efficiency. ApplicationIdSuffix 'test'// adds a suffix in applicationId, and not much versionNameSuffix' test'// adds a suffix in applicationId. Rarely used} debug {/ / Test environment buildConfigField ("boolean", "LOG_DEBUG", "true") / / configure Log log buildConfigField ("String", "URL_PERFIX", "\" https://test.com/\"")// configure whether the URL prefix minifyEnabled false// confuses proguardFiles getDefaultProguardFile ('proguard-android.txt')) 'proguard-rules.pro'// specifies the confusing rule file signingConfig signingConfigs.debug// setting signature information whether debuggable false// supports breakpoint debugging jniDebuggable false// can debug NDK code whether renderscriptDebuggable false// turns on rendering scripts that are some c-written rendering methods zipAlignEnabled true// performs ZIP alignment optimization on APK packages Reduce the size of zip, increase operational efficiency whether pseudoLocalesEnabled false// generates pseudo-language environment in APK to help internationalize things, generally used less applicationIdSuffix 'test'// adds a suffix in applicationId, less commonly used versionNameSuffix' test'// adds a suffix in applicationId Not many}} sourceSets {/ / directories are commonly used to point to the configuration main {jniLibs.srcDirs = ['libs'] / / specify the lib library directory}} packagingOptions {/ / the relevant configuration when packaging / / pickFirsts is used when there are duplicate files, the package will report an error so that the configuration will be packaged into apk with the first matching file / / indicates that when there is a duplicate META-INF directory in the apk When duplicate LICENSE files are packaged only with the first one so that there is no error pickFirsts = ['META-INF/LICENSE'] / / merges Why merge duplicate files when there are duplicate files and then package them into apk / / this has a default value merges = [] this will remove the silent value, so let's add merge' META-INF/LICENSE' after the default value in the following way / / this is when using butterknife, A process done by dagger2. By the same token, if you encounter a similar problem, just follow the hint of gradle and do similar treatment. Exclude 'META-INF/services/javax.annotation.processing.Processor'} productFlavors {wandoujia {} xiaomi {} _ 360 {} productFlavors.all {/ / batch modification, similar to a sequential traversal of flavor-> flavor.manifestPlaceholders = [IFLYTEK_CHANNEL: name]} / / the program checks lint when compiling, and stops build when prompted by any error We can turn off this switch lintOptions {abortOnError false / / does not stop packaging checkReleaseBuilds false / / package release versions to detect}} dependencies {/ / project dependencies implementation fileTree (include: ['* .jar'] Dir: 'libs') / / Local jar package depends on implementation' com.android.support:appcompat-v7:27.1.1' / / remote dependency on implementation 'com.android.support.constraint:constraint-layout:1.1.2' testImplementation' junit:junit:4.12' / / declares the test case library androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation' com.android.support.test.espresso:espresso-core:3.0.2 '} this is the end of the article on how to configure build.gradle in Android Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to configure build.gradle in Android". If you want to learn more, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.