37

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.

Community
  • 1
  • 1
Jan-Terje Sørensen
  • 14,468
  • 8
  • 37
  • 37
  • 1
    I'm reasonably certain you can't (easily). I think the goal is to have Eclipse ADT understand the build.gradle directly but that's still in the future, I'm afraid. – Delyan Jul 10 '13 at 13:28
  • Do you know why this is not a prioritized feature? Event better, do you know who to contact to get this feature going? – Jan-Terje Sørensen Jul 11 '13 at 15:09
  • 1
    I don't know anything more about their priorities than what's on [this list](http://tools.android.com/roadmap). That said, your best bet is to go to the [`adt-dev` mailing list](https://groups.google.com/forum/#!forum/adt-dev) and ask there (search first, though!). – Delyan Jul 12 '13 at 10:13
  • You can customize the gradle eclipse plugin, check my answer below. – Krishnaraj May 10 '14 at 11:51

6 Answers6

9

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.

Lii
  • 11,553
  • 8
  • 64
  • 88
S.D.
  • 29,290
  • 3
  • 79
  • 130
  • 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 ;) – Jan-Terje Sørensen Jul 12 '13 at 06:47
  • @arcone Ah.. I don't thing there's such a plug-in yet. Doesn't eclipse support importing Gradle projects ? – S.D. Jul 12 '13 at 06:52
  • 2
    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 Jul 12 '13 at 06:58
3

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.

Johannes Brodwall
  • 7,673
  • 5
  • 34
  • 28
  • 1
    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. https://github.com/greensopinion/gradle-android-eclipse – David Green Apr 23 '17 at 00:43
  • This worked. I need some help to convert this project into eclipse library. Any thoughts on that? – Govind Oct 31 '17 at 04:12
2

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

Project Member #2 x...@android.com

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

Community
  • 1
  • 1
Paul Verest
  • 60,022
  • 51
  • 208
  • 332
2

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

Krishnaraj
  • 2,360
  • 1
  • 32
  • 55
2

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.

David Green
  • 874
  • 7
  • 5
  • Thanks for this. Works well, and with the [Buildship](https://projects.eclipse.org/projects/tools.buildship) plugin for Eclipse I can run Android Gradle tasks on `build.gradle`. – mortalis Oct 09 '18 at 12:24
1

Maybe I'm missing something very obvious, but isn't the eclipse plugin what you're looking for? This generates a .project file as well as a .classpath file and updates these as needed when run subsequent times.

There is also an IDEA plugin, though I haven't used this one and can't speak to it.

Hope that helps.

Myles
  • 20,860
  • 4
  • 28
  • 37