Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Android Studio main SourceSet with Gradle API?

I'm working on developing a gradle plugin for Android Studio.Here is my problem How can I get Android Studio main SourceSet with Gradle API?

I want to do some copy stuff with java source directory. Before asking this question, I found something useful but not work.

SourceSet main = project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME)

I get this error message
Caused by: org.gradle.api.UnknownDomainObjectException: SourceSet with name 'main' not found.

like image 777
刘奔康 Avatar asked Oct 19 '22 09:10

刘奔康


2 Answers

First,the code doesn't work because it's only for the java project with java gradle plugin. So I googled and found something work around. Here is my code.

project.afterEvaluate {
    ...
    def sets;
    if (Utils.is140orAbove()) {
        sets = project.android.sourceSets;
    } else {
        sets = project.android.sourceSetsContainer;
    }
    sets.all { AndroidSourceSet sourceSet ->
        if(sourceSet.name.startsWith("main"))
            for(File file:sourceSet.java.getSrcDirs())
                if(file.exists()) {
                    mainSource = file;
                    break;
                }
    }
    ...
}

My code is not beautiful.Waiting for better answer.

like image 173
刘奔康 Avatar answered Oct 21 '22 06:10

刘奔康


android.sourceSets.main.java.getSrcDirs()[0].path

This works for me in Android Studio 3.1 and later

like image 22
Alexander Ushakov Avatar answered Oct 21 '22 06:10

Alexander Ushakov