How to exclude certain files from Android Studio gradle builds?

那年仲夏 提交于 2019-12-03 06:22:32

Looks like a recent change in gradle changed the DSL for sourceSets, so you now need to specify the exclude on the filter field:

android {
    sourceSets.main.res.filter.exclude '**/whatever.txt'
}

The Android plugin has its own concept of SourceSets: http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Configuring-the-Structure

So you'll probably want to do something like

android {
    sourceSets.main.res.exclude '**/whatever.txt'
}

In the child project, in your case I believe it is :APP, add the following to the build.gradle file.

packagingOptions {
    //Exclude the file(s) in this method. Provide the path and file name.    
    exclude 'src\main\res\layout\whatever.txt' 
}

The PackagingOptions DSL object allows you to control what files are included in the APK. exclude takes a string or pattern as an argument which will allow you to ignore files or directories by name or pattern.

EDIT Customizing which resources to keep from the Android Studio docs.

  1. Create XML file in your project with a <resources> tag.
  2. Add tools:keep="[list resources]"
  3. Add `tools:discard="[list resources]"
  4. Save the file in project resources at res/raw/keep.xml The build will not include this file.

The end file should look similar to the one in the Android Studio Docs

<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools"
    tools:keep="@layout/l_used*_c,@layout/l_used_a,@layout/l_used_b*"
    tools:discard="@layout/unused2" />

After much banging of head against keyboard, this worked for me:

apply plugin: 'com.android.library'

def getCurrentFlavor() {
    Gradle gradle = getGradle()
    String tskReqStr = gradle.getStartParameter().getTaskRequests().toString()

    Pattern pattern;

    if (tskReqStr.contains("assemble"))
        pattern = Pattern.compile("assemble(\\w+)(Release|Debug)")
    else
        pattern = Pattern.compile("generate(\\w+)(Release|Debug)")

    Matcher matcher = pattern.matcher(tskReqStr)

    if (matcher.find())
        return matcher.group(1).toLowerCase()
    else {
        println "NO MATCH FOUND"
        return "";
    }
}

android {
.
.
.
    sourceSets {
            main {
                if (getCurrentFlavor() == 'stripped') {
                    java.exclude('**/excluded1.java',
                    .
                    .)
            }
            java {
              srcDir 'main'
            }
          }
        } 
     }         

N.B. Credit to: How to get current flavor in gradle for writing the getCurrentFlavor method,

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!