Gradle核心之Project详解

news/2024/5/20 4:03:23 标签: android, gradle, Project

文章目录

  • project相关api
    • getAllprojects
    • getSubprojects
    • getParent
    • project
    • allprojects
    • subprojects
  • 属性相关api
    • 定义扩展属性
    • 定义扩展属性2
  • 文件属性
    • 路径获取相关api
    • 文件操作相关api
      • 文件定位
      • 文件拷贝
      • 文件树遍历
  • 其他api
  • 依赖相关api
    • buildscript
  • 执行外部命令

新建项目,添加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 }
	...

}

在这里插入图片描述

执行外部命令

在这里插入图片描述


http://www.niftyadmin.cn/n/1838334.html

相关文章

企业数据安全如何做,专家给你5条建议

引言&#xff1a;数据安全对企业生存发展有着举足轻重的影响&#xff0c;数据资产的外泄、破坏都会导致企业无可挽回的经济损失和核心竞争力缺失&#xff0c;而往往绝大多数中小企业侧重的是业务的快速发展&#xff0c;忽略了数据安全重要性。近年来&#xff0c;企业由于自身的…

opencv2/3.xx+vs2015配置过程

配置前期---系统及库的版本选择&#xff1a; 系统&#xff1a;win32 还是 win64&#xff1a;和你电脑是几位系统没关系&#xff0c;不要看你的电脑&#xff0c;要看开发的程序&#xff0c;如果开发win32程序&#xff0c;就要下载x86版本&#xff0c;当然要是win64程序&#xff…

DevExpress TreeList使用心得

最近做项目新增光纤线路清查功能模块&#xff0c;思路和算法已经想好了&#xff0c;些代码时候居然在一个控件上纠结了好长的时间&#xff0c;虽然后来搞定了&#xff0c;但是好记性不然烂笔头&#xff0c;还是写下来&#xff0c;以后要用到的时候直接翻就行&#xff0c;帮助文…

腾讯多媒体实验室重磅开源视频质量评估算法DVQA

近日&#xff0c;腾讯多媒体实验室设计的基于深度学习的全参考视频质量评估算法DVQA在Github上正式开源&#xff0c;该算法模型的性能目前在公开测试数据集上取得业界领先成绩。 开源地址&#xff1a;https://github.com/Tencent/DVQA 国内镜像地址&#xff1a; https://git.c…

第12课-动态规划

文章目录分治 回溯 递归 动态规划递归代码模版分治 Divide & Conquer感触动态规划 Dynamic Programming实战例题一 斐波拉契数列实战例题二 路径计数动态规划关键点实战例题三 最长公共子序列子问题DP 方程动态规划小结MIT algorithm course实战题目实战题目实战题目Hom…

腾讯会议如何做到8天扩容100万核?

原文链接&#xff1a;腾讯会议如何做到8天扩容100万核&#xff1f; 疫情期间&#xff0c;腾讯会议作为一款非常便捷的远程协作工具&#xff0c;成为国内众多企业日常会议沟通交流的主要平台。殊不知&#xff0c;这款产品从2019年12月26日才正式推出。如何在这么短的时间内&…

“用云的方式保护云”: 如何利用云原生SOC进行云端检测与响应

传统企业安全中&#xff0c;部署了EDR&#xff08;Endpoint Detection and Response&#xff09;及NDR&#xff08;Network Detection and Response&#xff09;产品的企业&#xff0c;可及时定位失陷资产&#xff0c;响应终端威胁&#xff0c;减少攻击产生的危害。EDR和NDR在传…

VR/ AR/ MR/ CR/ XR/ AV的区别及简介

VR Virtual Reality&#xff0c;虚拟现实&#xff0c;算是这块地头的老大哥了&#xff0c;长兄如父&#xff0c;之后的相关概念&#xff0c;也大都是基于VR衍生出来的。 官方一点的说法是&#xff0c;VR技术是一种可以创建和体验虚拟世界的计算机仿真系统&#xff0c;它利用计…