treesAreEverywhere
treesAreEverywhere

Reputation: 3972

In Android, compiling with Gradle, how to share code between projects?

What is the preferred way to share some code (E.g. a Utils class) between two projects when building two apps using Gradle to build?

Can I do this without creating extra jar files? I just want my code to sit outside the app projects, be imported/compiled into both app projects. Or is this simply not possible?

I'm familiar with the approach that uses jars or Android library projects, but both seem a bit unwieldy.

Upvotes: 3

Views: 234

Answers (1)

Krylez
Krylez

Reputation: 17800

My favorite way of doing this is by keeping it in a local Maven repo. The repo can even live in your SCM so it's the same across workspaces.

Create a new Android Studio project and then set it as a maven project your build.gradle config:

buildscript {
    repositories {
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:0.6.+'
    }
}
apply plugin: 'android-library'
apply plugin: 'maven'

repositories {
    mavenCentral()
}

configurations {
    archives {
        extendsFrom configurations.default
    }
}

group = 'com.mypackage.mylibrary'
version = '1.0.0'

uploadArchives {
    configuration = configurations.archives
    repositories {
        mavenDeployer {
            repository(url: uri("relative/path/to/localrepo"))
            pom.project {
                artifactId 'mylibrary'
                name 'My Library'
                packaging 'aar'
            }
        }
    }
}
android {
    // copy old android config here
}

You'll need to deploy the library before you can use it. Do this by using the uploadArchives task [./gradlew uploadArchives]

Now you should be able to use this library in any project by doing this:

repositories {
    maven { url 'relative/path/to/localrepo' }
}
dependencies {
    compile ('com.mypackage.mylibrary:1.0.0')
}

When you make changes to your library, you'll have to re-deploy (uploadArchives) with a new version, then update the dependency reference in whatever project needs the new version.

Upvotes: 3

Related Questions