build.gradle in the project vs. build.gradle in th

2020-07-09 09:51发布

问题:

I started a project in Android Studio, with IntelliJ.

The project includes two files called build.gradle. One is under the folder app, and one is under the main folder which is my project name, say MyProject.

Why the need for two? What is the difference between the two build.gradles?

回答1:

Android Studio project consists of modules, libraries, manifest files and Gradle build files.

Each project contains one top-level Gradle build file. This file is named build.gradle and can be found in the top level directory.

This file usually contains common config for all modules, common functions..

Example:

  //gradle-plugin for android
  buildscript {
    repositories {
        mavenCentral()  //or jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:0.12.2'        
    }
  }

  // common variables
  ext {
     compileSdkVersion = 19
     buildToolsVersion = "20.0.0"
  }

  // a custom function
  def isReleaseBuild() {
     return version.contains("SNAPSHOT") == false
  }

  //common config for all projects
  allprojects {
     version = VERSION_NAME

     repositories {
       mavenCentral()
     }
  }

All modules have a specific build.gradle file. This file contains all info about this module (because a project can contain more modules), as config,build tyoes, info for signing your apk, dependencies....

Example:

apply plugin: 'com.android.application'


android {
    //These lines use the constants declared in top file
    compileSdkVersion rootProject.ext.compileSdkVersion
    buildToolsVersion rootProject.ext.buildToolsVersion

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 19
        versionName project.VERSION_NAME  //it uses a property declared in gradle.properties
        versionCode Integer.parseInt(project.VERSION_CODE) 
    }

    // Info about signing
    signingConfigs {
        release
    }

    // Info about your build types
    buildTypes {
        if (isReleaseBuild()) {
            release {
                signingConfig signingConfigs.release
            }
        }

        debug {
            applicationIdSuffix ".debug"
            versionNameSuffix "-debug"
        }
    }

    // lint configuration
    lintOptions {
        abortOnError false
    }
}

//Declare your dependencies  
dependencies {
    //Local library
    compile project(':Mylibrary')
    // Support Libraries
    compile 'com.android.support:support-v4:20.0.0'
    // Picasso
    compile 'com.squareup.picasso:picasso:2.3.4'

}

You can find more info here: http://developer.android.com/sdk/installing/studio-build.html