Android Studio: “new module -> import existing project” vs. “import module”

melvynkim picture melvynkim · Oct 14, 2014 · Viewed 66.9k times · Source

What I have:

Four independently working Android modules:

  1. MyProjectMainModule, a main container application, attached to MyProject

  2. MyGradleModule, a library, with all necessary components built during gradlew process.

  3. MyPreGradleModule, a library, with src/, res/, AndroidManifest.xml, and pom.xml, without gradle wrapper

  4. MyRawModule, a library, with src/, res/, AndroidManifest.xml, without pom.xml (commonly seen in Ant-based Eclipse projects)

What I'd like to achieve:

To import all three modules (i.e. MyGradleModule, MyPreGradleModule, MyRawModule) into MyProject as dependencies of MyProject. The complete project structure should resemble below project structure:

MyProject
|--MyProjectMainModule
|--MyGradleModule
|--MyPreGradleModule
|--MyRawModule

Question:

Realizing all three modules (MyGradleModule, MyPreGradleModule, and MyRawModule) have different structures, what are the most optimal ways to import each modules with minimal efforts?

Could you please match one of the following Android Studio menu items with each modules in your answer (if you use any):

  1. File -> Import Module...
  2. File -> New Module... -> Import Existing Project
  3. File -> New Module... -> Android Library

Answer

Mike Laren picture Mike Laren · Oct 14, 2014

You can add the three modules to the same project by creating a settings.gradle file in the MyProject/ folder and adding the modules to it:

include ':MyGradleModule'
include ':MyPreGradleModule'
include ':MyRawModule'

Then for each module, configure the build.gradle dependencies to reference the other modules as needed. For example, add this to the MyProjectMainModule to make it use the output produced by MyGradleModule:

dependencies {
  compile project(':MyGradleModule')
}

Finally, if your project has heterogeneous submodules then you can configure their structure using the 'sourceSets' closure. For example, your raw module would have a configuration similar to this:

android {
    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }
        androidTest.setRoot('tests')
    }
}

Check out this section of the Gradle Plugin Guide to see what configuration options are available.