Gradle核心之Project详解

新建项目,添加lib_a、lib_b、lib_c三个module
在命令行中输入: ./gradlew projects

在这里插入图片描述

是否是gradle项目,是看目录下是否有build.gradle文件


project相关api

在这里插入图片描述


getAllprojects

在根目录的build.gradle文件中添加

获取工程所有project

this.getProjects()

def getProjects(){
    this.getAllprojects().eachWithIndex{ Project project, int index ->
        if(index == 0){
            println "Root project : ${project.name}"
        }else{
            println "+--- project : ${project.name}"
        }

    }
}
Root project : gradle_project
+--- project : app
+--- project : lib_a
+--- project : lib_b
+--- project : lib_c

getSubprojects

获取所有子project

def getProjects(){
    this.getSubprojects().eachWithIndex{ Project project, int index ->
        println "+--- project : ${project.name}"
    }
}
+--- project : app
+--- project : lib_a
+--- project : lib_b
+--- project : lib_c

getParent

获取父project

在lib_a的build.gradle文件中添加

this.getParentProject()
def getParentProject(){
    def pname = this.getParent().name;
    println "the parent project name is:${pname}"
}

the parent project name is:gradle_project


获取根project

this.getRootPro()
def getRootPro(){
    def name = this.getRootProject().name;
    println "the root project name is:${name}"
}

the root project name is:gradle_project


project

操作指定project
在根build.gradle中添加如下:

project('app'){Project project ->
    println project.name
}

app


project('app'){Project project ->
    apply plugin: 'com.android.application'
    android {
    }
    dependencies {   
    }
}

所以如果愿意的话,可以将app的build.gradle内容全部写在根目录的build.gradle中


allprojects

//配置当前结点工程和其subproject的所有project
allprojects {
    group 'com.hongx'
    version '1.0.0-release'
}

println project('app').group
println project('app').version

com.hongx
1.0.0-release


subprojects

//不包括当前结点工程,只包括它的subproject
subprojects { Project project ->
    //只为库工程引入maven发布功能
    if (project.plugins.hasPlugin('com.android.library')) {
        apply from: '../publishToMaven.gradle'
    }
}

属性相关api

Project中几个默认的属性

public interface Project extends Comparable<Project>, ExtensionAware, PluginAware {
    /**
     * The default project build file name.
     */
    String DEFAULT_BUILD_FILE = "build.gradle";

    /**
     * The hierarchy separator for project and task path names.
     */
    String PATH_SEPARATOR = ":";

    /**
     * The default build directory name.
     */
    String DEFAULT_BUILD_DIR_NAME = "build";

    String GRADLE_PROPERTIES = "gradle.properties";

...

我们还可以扩展自己想要的属性

定义扩展属性

//定义扩展属性
ext{
    compileSdkVersion = 29
}
android {
    compileSdkVersion this.compileSdkVersion
	
	...
	    
}

我们可以在根工程的build.gradle中为每个自工程定义ext属性

subprojects {
    ext{
        compileSdkVersion = 28
        buildToolsVersion = '28.0.0'
    }
}

同样在app或者其他自工程中可以使用自定义的属性

android {
    compileSdkVersion this.compileSdkVersion
    buildToolsVersion this.buildToolsVersion

	...

}

我们也可以自定义一个common.gradle来用于自定义属性,此时需要在根工程的build.gradle中引入common.gradle

apply from: this.file('common.gradle')
//用来存放应用中的所有配置变量,统一管理,而不再是每个moudle里都自己写一份,修改起来更加的方便

ext {

  android = [compileSdkVersion   : 25,
             buildToolsVersion   : '25.0.0',
             applicationId       : 'com.youdu',
             minSdkVersion       : 16,
             targetSdkVersion    : 23,
             versionCode         : 1,
             versionName         : '1.0.0',
             multiDexEnabled     : true,
             manifestPlaceholders: [UMENG_CHANNEL_VALUE: 'imooc']]

  signConfigs = ['storeFile'    : 'abc.jks',
                 'storePassword': '123456',
                 'keyAlias'     : 'abc',
                 'keyPassword'  : '123456']

  java = ['javaVersion': JavaVersion.VERSION_1_7]


  dependence = ['libSupportV7'           : 'com.android.support:appcompat-v7:25.0.0',
                'libSupportMultidex'     : 'com.android.support:multidex:1.0.1',
                'libCommonLibrary'       : ':vuandroidadsdk',
                'libPullAlive'           : ':lib_pullalive',
                'libCircleImageView'     : 'de.hdodenhof:circleimageview:2.1.0',
                'libSystembarTint'       : 'com.readystatesoftware.systembartint:systembartint:1.0.3',
                'libUmengAnalytics'      : 'com.umeng.analytics:analytics:latest.integration',
                'libUniversalImageLoader': 'com.nostra13.universalimageloader:universal-image-loader:1.9.5',
                'libOkhttp'              : 'com.squareup.okhttp3:okhttp:3.3.0',
                'libAutoScrollViewPager' : 'cn.trinea.android.view.autoscrollviewpager:android-auto-scroll-view-pager:1.1.2',
                'libSlidableActivity'    : 'com.r0adkll:slidableactivity:2.0.5',
                'libAndfix'              : 'com.alipay.euler:andfix:0.5.0@aar',
                'libLogger'              : 'com.orhanobut:logger:+',
                'libTinker'              : "com.tencent.tinker:tinker-android-lib:1.7.7",
                'libTinkerAndroid'       : "com.tencent.tinker:tinker-android-anno:1.7.7"]
}

定义扩展属性2

在gradle.properties文件中添加

isLoadLibA=true

在settings.gradle中修改

if(hasProperty(isLoadLibA) ? isLoadLibA.toBoolean() : false){
    include ':lib_a'
}

文件属性

在这里插入图片描述

路径获取相关api

获取路径

println getRootDir().absolutePath
println getBuildDir().absolutePath
println getProjectDir().absolutePath

文件操作相关api

文件定位

println getContent('common.gradle')
def getContent(String path){
    try{
        def file = file(path)
        return file.text
    }catch(GradleException e){
        println 'file not found'
    }
}

文件拷贝

将abc.jks 拷贝到build目录下

copy {
    from file('abc.jks')
    into getRootProject().getBuildDir()
}

当然copy也可以进行文件夹的拷贝


文件树遍历

fileTree('build/outputs/apk') { FileTree fileTree ->
    fileTree.visit { FileTreeElement element ->//树中的每个节点
        println 'the file name is :' + element.file.name
        copy {
            from element.file
            into getRootProject().getBuildDir().path + '/test/'

        }
    }
}

其他api

依赖相关api

buildscript

根build.gradle中:

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.4.2'
    }
}

查看其源码
在这里插入图片描述

从上面源码解释中可以看出,buildscript的闭包参数是ScriptHandler

public interface ScriptHandler {
    /**
     * The name of the configuration used to assemble the script classpath.
     */
    String CLASSPATH_CONFIGURATION = "classpath";

	...
	   /**
     * Configures the repositories for the script dependencies. Executes the given closure against the {@link
     * RepositoryHandler} for this handler. The {@link RepositoryHandler} is passed to the closure as the closure's
     * delegate.
     *
     * @param configureClosure the closure to use to configure the repositories.
     */
    void repositories(Closure configureClosure);
	...
	 /**
     * Configures the dependencies for the script. Executes the given closure against the {@link DependencyHandler} for
     * this handler. The {@link DependencyHandler} is passed to the closure as the closure's delegate.
     *
     * @param configureClosure the closure to use to configure the dependencies.
     */
    void dependencies(Closure configureClosure);

	...

repositories的闭包参数是RepositoryHandler
dependencies的闭包参数是DependencyHandler


写成闭包形式

buildscript { ScriptHandler scriptHandler ->
    //配置我们工程的仓库地址
    scriptHandler.repositories { RepositoryHandler repositoryHandler ->
        repositoryHandler.google()
        repositoryHandler.jcenter()
        repositoryHandler.maven {
            name 'personal'
            url 'http://localhost:8081/nexus/repositories'
            credentials {
                username = 'admin'
                password = 'admin123'
            }
        }
    }
    //配置我们工程的"插件"依赖地址(gradle要使用的插件),注意与Project(应用程序)的dependencies区分开来
    scriptHandler.dependencies { DependencyHandler dependencyHandler ->
        classpath 'com.android.tools.build:gradle:3.4.2'
    }
}


//为应用程序添加第三方库依赖
dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile rootProject.ext.dependence.libSupportV7
    compile rootProject.ext.dependence.libSupportMultidex
    //依赖library工程
    compile project(rootProject.ext.dependence.libCommonLibrary)
    compile project(rootProject.ext.dependence.libPullAlive)
    compile rootProject.ext.dependence.libCircleImageView
    compile rootProject.ext.dependence.libSystembarTint

  	compile(rootProject.ext.dependence.libAutoScrollViewPager) {
        exclude module: 'support-v4' //排除依赖
        transitive false //禁止传递依赖
    }	
    //Tinker相关依赖
    compile(rootProject.ext.dependence.libTinker) {
        changing = true //每次都从服务端拉取
    }
    provided(rootProject.ext.dependence.libTinkerAndroid) { changing = true }
	...

}

在这里插入图片描述

执行外部命令

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值