Using Gradle with an existing Android project

woot picture woot · Jun 26, 2013 · Viewed 12.9k times · Source

I have an existing Android project with the following structure:

- ProjectName
-- AndroidManifest.xml
-- local.properties
-- project.properties

-- assets
-- libs    (containing all jars)
-- modules (containing all library projects my project depends on)
-- res

-- src
---- com/namespace/projectname (all my classes including main activity are here)

I haven't been using any specific build system to build my project other than the one provided by default with the Android Studio IDE (though the project was originally created with IntelliJ CE.

I would like to use Gradle with the android plugin and do some work on my build process. I have tried several configurations in order to achieve this and have failed to complete a successful build every time.

What's the recommended approach in this scenario? should I change my project structure? or is it possible to configure gradle using the existing structure?

Any help would be greatly appreciated.

Thanks!

Answer

rivare picture rivare · Jun 26, 2013

Just install gradle on your computer und make sure all paths are ok.

After that create a "build.gradle" file in your Project folder.

Here an basic example your can start from:

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:0.4.+'
    }
}

apply plugin: 'android'

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    compile project(':yourModuleName') 
}

android {
    compileSdkVersion 17
    buildToolsVersion "17.0.0"

    defaultConfig {
        minSdkVersion 10
        targetSdkVersion 16
    }

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        instrumentTest.setRoot('yourTestRoot')
    }
}

To adress your modules like I did in the dependenciey block, you have to create a settings.gradle file and reference your modules as project. Since i assume they have also a custom layout, you have to make build.gradle files on the module folder too.

For the settings.gradle setup you should visit the gradle documentation, nothing android specific here.