How to use Gradle to generate Eclipse and Intellij project files for Android projects

49,588

Solution 1

Gradle itself is a generic build tool, it is not created specifically for Android.

All the functionality is enabled using plug-ins. Traditionally, build plug-ins don't generate project structure. That's the job of project specific tools. The Android plug-in for Gradle follows this.

The problem is that current android tool in SDK generates old type of project structure (ant builds). The new project structure can only be generated via Android Studio.

There is a concept of archetypes in tools like Maven, which allow using project templates. Gradle does not support that yet (requests have been made for this feature).

Refer to this thread: http://issues.gradle.org/browse/GRADLE-1289 , some users have provided scripts to generate structure.

Build Initialization feature is in progress: https://github.com/gradle/gradle/blob/master/design-docs/build-initialisation.md

Hopefully some one can write a script to do that, refer to this guide for new project structure: http://tools.android.com/tech-docs/new-build-system/user-guide

Update

There is now an official Android IDE: Android Studio . It is based on Intellij and the new build system is Gradle based.

Solution 2

There are four issues with the combination of the Gradle plugins 'com.android.application' and 'eclipse': First, the configuration classpaths are not added to Eclipse's classpath, but this is easy to fix. Second, something must be done about the .AAR-dependencies. This was a bit trickier. Third, we need to include the generated sources for things like R.java. Finally, we need to include Android.jar itself.

I was able to hack together a gradle configuration that would generate proper .classpath files for Eclipse from an Android Studio build.config. The effects were very satisfying to my CPU fan, which had been running constantly with Android Studio. Eclipse sees the resulting project as a fully functional Java project, but only that.

I ended up putting the following directly in build.gradle in my app-project:

apply plugin: 'eclipse'
eclipse {
    pathVariables 'GRADLE_HOME': gradle.gradleUserHomeDir, "ANDROID_HOME": android.sdkDirectory 
    classpath {
        plusConfigurations += [ configurations.compile, configurations.testCompile ]

        file {
            beforeMerged { classpath ->
                classpath.entries.add(new org.gradle.plugins.ide.eclipse.model.SourceFolder("src/main/java", "bin"))
                // Hardcoded to use debug configuration
                classpath.entries.add(new org.gradle.plugins.ide.eclipse.model.SourceFolder("build/generated/source/r/debug", "bin"))
                classpath.entries.add(new org.gradle.plugins.ide.eclipse.model.SourceFolder("build/generated/source/buildConfig/debug", "bin"))
            }

            whenMerged { classpath ->
                def aars = []
                classpath.entries.each { dep ->
                    if (dep.path.toString().endsWith(".aar")) {
                        def explodedDir = new File(projectDir, "build/intermediates/exploded-aar/" + dep.moduleVersion.group + "/" + dep.moduleVersion.name + "/" + dep.moduleVersion.version + "/jars/")
                        if (explodedDir.exists()) {
                            explodedDir.eachFileRecurse(groovy.io.FileType.FILES) {
                                if (it.getName().endsWith("jar")) {
                                    def aarJar = new org.gradle.plugins.ide.eclipse.model.Library(fileReferenceFactory.fromFile(it))
                                    aarJar.sourcePath = dep.sourcePath
                                    aars.add(aarJar)
                                }
                            }
                        } else {
                            println "Warning: Missing " + explodedDir
                        }
                    }
                }
                classpath.entries.removeAll { it.path.endsWith(".aar") }
                classpath.entries.addAll(aars)

                def androidJar = new org.gradle.plugins.ide.eclipse.model.Variable(
                    fileReferenceFactory.fromPath("ANDROID_HOME/platforms/" + android.compileSdkVersion + "/android.jar"))
                androidJar.sourcePath = fileReferenceFactory.fromPath("ANDROID_HOME/sources/" + android.compileSdkVersion) 
                classpath.entries.add(androidJar)
            }
        }
    }
}

// We need build/generated/source/{r,buildConfig}/debug to be present before generating classpath
//  This also ensures that AARs are exploded 
eclipseClasspath.dependsOn "generateDebugSources"


// Bonus: start the app directly on the device with "gradle startDebug"
task startDebug(dependsOn: "installDebug") << {
    exec {
        executable = new File(android.sdkDirectory, 'platform-tools/adb')
        args = ['shell', 'am', 'start', '-n', android.defaultConfig.applicationId + '/.MainActivity']
    }
}

Run gradle eclipse and you will have an Eclipse-project that can be imported and compiled. However, this project acts as a normal Java-project. In order to build the apk, I have to drop back to gradle command line and execute gradle installDebug. gradle processDebugResources picks up changes in Android XML files and regenerates the files under build/generated/source. I use the "monitor" program with Android SDK to view the app logs. I have so far not found any way to debug without Android Studio.

The only features I miss from Android Studio are debugging (but who has time for bugs!) and editing resources visually.

Solution 3

The following worked for me

eclipse.classpath.plusConfigurations += configurations.compile

eclipse.classpath.file {
    beforeMerged { classpath ->
    classpath.entries.removeAll() { c -> 
        c.kind == 'src'
    }
}

withXml {
    def node = it.asNode()

    node.appendNode('classpathentry kind="src" path="src/main/java"')
    node.appendNode('classpathentry kind="src" path="src/debug/java"')
    node.appendNode('classpathentry kind="src" path="gen"')

    node.children().removeAll() { c ->
        def path = c.attribute('path')
        path != null && (
                path.contains('/com.android.support/support-v4')
                )
    }
  }
}

eclipse.project {
   name = 'AndroidGradleBasic'

   natures 'com.android.ide.eclipse.adt.AndroidNature'
   buildCommand 'com.android.ide.eclipse.adt.ResourceManagerBuilder'
   buildCommand 'com.android.ide.eclipse.adt.PreCompilerBuilder'
   buildCommand 'com.android.ide.eclipse.adt.ApkBuilder'
}

Source - http://blog.gouline.net/2013/11/02/new-build-system-for-android-with-eclipse/

Sample - https://github.com/krishnaraj/oneclipboard

Solution 4

As answered in Issue 57668 by Android team (raised by @arcone)

Project Member #2 [email protected]

The eclipse plugin is not compatible with the android plugin.

You will not be able to import an Android gradle project into Eclipse using the default Gradle support in Eclipse.

To make it work in Eclipse we will have to change the Gradle plugin for Eclipse, the same way we are modifying the Gradle support in IntelliJ

That is Android team is working on gradle plugin for IntelliJ and gradle plugin for Eclipse needs to be updated too.

What is possible with Eclipse now is

.1. import the project as general project

.project

<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
    <name>OpenSpritz-Android</name>
    <comment></comment>
    <projects>
    </projects>
    <buildSpec>
    </buildSpec>
    <natures>
    </natures>
</projectDescription>

import-android-gradle-as-general-project

.2. Put 2 Eclipse . "dot" files into modules into /OpenSpritz-Android/app/src/main and /OpenSpritz-Android/lib/src/main

add-eclipse-files

.project

<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
    <name>OpenSpritz-Android-app</name>
    <comment></comment>
    <projects>
    </projects>
    <buildSpec>
        <buildCommand>
            <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.eclipse.jdt.core.javabuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>com.android.ide.eclipse.adt.ApkBuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
        <nature>org.eclipse.jdt.core.javanature</nature>
    </natures>
</projectDescription>

.classpath

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" path="java"/>
    <classpathentry kind="src" path="gen"/>
    <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
    <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
    <classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
    <classpathentry kind="output" path="bin/classes"/>
</classpath>

.3. Import as Existing Android Code into Workspace

results

you can then browse code in familiar way, but even after that you won't be able to run with Eclipse ADT.

.4.

Now you can run build and tasks with gradle CLI or Nodeclipse/Enide Gradle for Eclipse (marketplace)

start

discuss at https://github.com/Nodeclipse/nodeclipse-1/issues/148

Solution 5

I've created a new Gradle plugin that generates the appropriate Eclipse .project and .classpath files, based on the answer provided by Johannes Brodwall on this stack overflow.

See https://github.com/greensopinion/gradle-android-eclipse for details.

Share:
49,588
Jan-Terje Sørensen
Author by

Jan-Terje Sørensen

Updated on July 10, 2022

Comments

  • Jan-Terje Sørensen
    Jan-Terje Sørensen almost 2 years

    Is it possible to generate Eclipse and Intellij project files for Android projects using Gradle?

    In maven we would do mvn eclipse:eclipse and in PlayFramework we would do play eclipsify. Does Gradle have this feature for Android projects?

    I have installed Gradle (1.6) and Android SDK Manager (22.0.1) explained here

    This is my build.gradle file:

    buildscript {
        repositories {
          mavenCentral()
        }
        dependencies {
          classpath 'com.android.tools.build:gradle:0.5.0'
        }
    }
    
    apply plugin: 'android'
    apply plugin: 'eclipse'
    
    sourceCompatibility = 1.7
    version = '1.0.2'
    
    repositories {
        mavenCentral()
    }
    
    dependencies {
      compile fileTree(dir: 'libs', include: '*.jar')
    }
    
    android {
        buildToolsVersion "17" 
        compileSdkVersion 8
        defaultConfig {
            versionCode 1
            versionName "1.0"
            minSdkVersion 7
            targetSdkVersion 8
        }
        sourceSets {
            main {
                  manifest.srcFile 'AndroidManifest.xml'
                  java.srcDirs = ['src']
                  resources.srcDirs = ['src']
                  aidl.srcDirs = ['src']
                  renderscript.srcDirs = ['src']
                  res.srcDirs = ['res']
                  assets.srcDirs = ['assets']
            }
            instrumentTest.setRoot('tests')
        }
    }
    

    And then I run the command:

    gradle clean build cleanEclipse eclipse
    

    It builds just fine, but when I import the project into Eclipse it looks like a normal java project.

    Anyone know how to get Gradle to create Android specific Eclipse project files?

    Is this a prioritized feature by Gradle?

    -- UPDATE --

    I do believe this is an issue. So I have posted it to the Android Tools team issue #57668. Please star it for them to prioritize the issue :)

    -- UPDATE --

    It does not look like the Android Tools team are looking into this issue. So for now I have converted to Android Studio where I'm able to import my gradle project with dependencies via the IDE.

  • Jan-Terje Sørensen
    Jan-Terje Sørensen almost 11 years
    I'm not looking for a Gradle way to create archetypes. What I'm after is the generation of IDE specific projects files, that enables me to import as project in my prefered IDE. In maven we would do mvn eclipse:eclipse, and in Play Framework we would do play eclipsify. I gave +1 for getting the discussion started ;)
  • S.D.
    S.D. almost 11 years
    @arcone Ah.. I don't thing there's such a plug-in yet. Doesn't eclipse support importing Gradle projects ?
  • Jan-Terje Sørensen
    Jan-Terje Sørensen almost 11 years
    I have installed the Gradle plugin for eclipse, and it did not seem to work. I should add that I have not tryed this much, because I dont want that extra complexity. I sure would love to have a gradle eclipse command that would handle android projects :)
  • Jan-Terje Sørensen
    Jan-Terje Sørensen almost 11 years
    As of what I understand the gradle eclipse plugin only generate java project files and not Android :-(
  • Myles
    Myles almost 11 years
    Ah, that would be the obvious piece I was missing. Might be a good starting point though.
  • David Green
    David Green about 7 years
    This worked so well for me that I've created a Gradle plugin to do this. Modified slightly to work with the new Android build system. github.com/greensopinion/gradle-android-eclipse
  • Govind
    Govind over 6 years
    This worked. I need some help to convert this project into eclipse library. Any thoughts on that?
  • mortalis
    mortalis over 5 years
    Thanks for this. Works well, and with the Buildship plugin for Eclipse I can run Android Gradle tasks on build.gradle.