Michigan Labs Logo

Making your Android project modular with convention plugins

User sitting at desk typing into a MacBook computer

If you're like us, Gradle and other build tools can seem like magic bundles of text that just happen to build a functioning application.

Over time, we've begun to better understand build tools like Gradle. As an Android project grows, you'll likely need to separate code into modules to decouple dependencies and enable team members to work on different modules without conflicts.

In this blog, we'll discuss how we can make the process smoother with gradle convention plugins.

Before and after

When creating an Android module from scratch within Android Studio, you'll end up with a Gradle build file that looks something like the below (we're using Kotlin DSL `.kts` files and a central `libs.version.toml` file; they're great):

1plugins {
2 alias(libs.plugins.com.android.library)
3 alias(libs.plugins.org.jetbrains.kotlin.android)
4}
5
6android {
7 namespace = "com.example.myexamplelibrary"
8 compileSdk = 34
9
10 defaultConfig {
11 minSdk = 24
12
13 testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
14 consumerProguardFiles("consumer-rules.pro")
15 }
16
17 buildTypes {
18 release {
19 isMinifyEnabled = false
20 proguardFiles(
21 getDefaultProguardFile("proguard-android-optimize.txt"),
22 "proguard-rules.pro"
23 )
24 }
25 }
26 compileOptions {
27 sourceCompatibility = JavaVersion.VERSION_1_8
28 targetCompatibility = JavaVersion.VERSION_1_8
29 }
30 kotlinOptions {
31 jvmTarget = "1.8"
32 }
33}
34
35dependencies {
36 implementation(libs.core.ktx)
37 implementation(libs.androidx.appcompat)
38 implementation(libs.material)
39 testImplementation(libs.junit)
40 androidTestImplementation(libs.androidx.test.ext.junit)
41 androidTestImplementation(libs.espresso.core)
42}

You'll see that we already have 43 lines of code by default, including many magic numbers for SDK versions and Java compatibility. One way to remove the hard coded constants and share them with other modules is to pull them out into variables through `buildSrc` or into your `libs.version.toml`. But what if we took it further? We could condense it down to something like:

1plugins {
2 id("android-library-convention")
3}
4
5android {
6 namespace = "com.example.myexamplelibrary"
7}
8
9dependencies {
10 ...any extra dependencies needed for this module
11}

All of the repeated configuration we typically have to do inside of the `android` configuration block is now gone. But, obviously it's just moved elsewhere, right?

It is, but now we're able to specify a convention plugin at the top of our library modules and inject the configuration we know we need.

How do we define the convention plugins?

Below, I'll list the steps I took to create convention plugins for my project.

- Create a directory at the base of your project called `build-logic`.

- Create a kotlin/java module inside of that directory and name it `convention` (you can change the name of these but to match the directions below they'll need to match). You should now have a source folder and a `build.gradle.kts` file inside of the `convention` directory. We'll edit the build file in a bit.

- Make sure you're using a `libs.versions.toml` file in your root project's gradle folder. Setup instructions for that can be found at the link above.

- Add a `settings.gradle.kts` file to the `build-logic` directory with contents of:

1dependencyResolutionManagement {
2 repositories {
3 google()
4 gradlePluginPortal()
5 mavenCentral()
6 }
7 versionCatalogs {
8 create("libs") {
9 from(files("../gradle/libs.versions.toml"))
10 }
11 }
12}
13
14rootProject.name = "build-logic"
15include(":convention")

Now, we'll fill out the `build.gradle.kts` inside of `convention` module, the `jvmToolchain` version and dependencies for this module will change based on what JVM version your project needs and what dependencies you're trying to reuse across the project.

In my project I am making reusable plugins for `android` libraries and `hilt` setup currently:

1plugins {
2 // Needed to define our future convention plugin files using kotlin DSL syntax
3 `kotlin-dsl`
4}
5
6group = "com.example.buildlogic"
7
8kotlin {
9 jvmToolchain(17)
10}
11
12dependencies {
13// Comments below indicate what the reference in `libs.versions.toml` look like, the first is from `[versions]` and the second is the listing in `[libraries]`
14// agp = 8.1.4
15// com-android-gradle-plugin = { group = "com.android.tools.build", name = "gradle", version.ref = "agp" }
16 implementation(libs.com.android.gradle.plugin)
17
18// org-jetbrains-kotlin-android = "1.9.22"
19// org-jetbrains-kotlin-android-gradle-plugin = { group = "org.jetbrains.kotlin", name = "kotlin-gradle-plugin", version.ref = "org-jetbrains-kotlin-android" }
20 implementation(libs.org.jetbrains.kotlin.android.gradle.plugin)
21// ksp = "1.9.22-1.0.17"
22// ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" }
23 implementation(libs.com.google.devtools.ksp.plugin)
24// hilt = "2.50"
25// hilt-gradle-plugin = { group = "com.google.dagger", name = "hilt-android-gradle-plugin", version.ref = "hilt" }
26 implementation(libs.hilt.gradle.plugin)
27}

You'll notice that we are specifying these as libraries, not plugins. That's because these plugin libraries are dependencies required by the convention plugins, rather than being directly using them as plugins within our Android modules as we typically do.

Now go to the base `settings.gradle.kts` at the root of your project and add `build-logic` as an included build:

1pluginManagement {
2 includeBuild("build-logic")
3 repositories {
4 google()
5 mavenCentral()
6 gradlePluginPortal()
7 }
8}

Time for the fun part: actually filling out the convention module with convention plugins. You could do this with just writing the plugins as Kotlin classes `class AndroidLibraryConventionPlugin : Plugin<Project> {`, but we chose to use a mix of Kotlin extension syntax and Kotlin DSL syntax in gradle.

If you want to create a convention plugin for reuse in all of your Android libraries, you can create a `android-library-convention.gradle.kts` file inside of `src/main/kotlin`. (The file name is up to you, but will impact what name you need to use to import this plugin later).

Here is what the Android library plugin looks like:

1plugins {
2 id("com.android.library")
3 kotlin("android")
4}
5
6android {
7 commonConfiguration(this)
8}
9
10kotlin {
11 configureKotlinAndroid(this)
12}

It's really simple, but what are these `commonConfiguration` and `configureKotlinAndroid` functions doing? They are just functions defined in an `ext` directory alongside the plugin folders. We have an `AndroidExt.kt` file with the contents of:

1import com.android.build.api.dsl.CommonExtension
2import org.gradle.api.artifacts.VersionCatalogsExtension
3import org.jetbrains.kotlin.gradle.dsl.KotlinAndroidProjectExtension
4
5fun org.gradle.api.Project.commonConfiguration(
6 extension: CommonExtension<*, *, *, *, *>
7) = extension.apply {
8 compileSdk = versionCatalog.findVersion("compile-sdk").get().requiredVersion.toInt()
9
10 defaultConfig {
11 minSdk = versionCatalog.findVersion("min-sdk").get().requiredVersion.toInt()
12 testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
13 }
14 buildFeatures {
15 buildConfig = true
16 }
17}
18
19fun org.gradle.api.Project.configureKotlinAndroid(
20 kotlinAndroidProjectExtension: KotlinAndroidProjectExtension
21) {
22 kotlinAndroidProjectExtension.apply {
23 jvmToolchain(17)
24 }
25}
26
27val org.gradle.api.Project.versionCatalog
28 get() = extensions.getByType(VersionCatalogsExtension::class.java)
29 .named("libs")

and a `Utilities.kt` file that currently just has:

1package ext
2
3import org.gradle.api.Project
4import org.gradle.api.artifacts.VersionCatalog
5import org.gradle.api.artifacts.VersionCatalogsExtension
6
7val Project.libs: VersionCatalog
8 get() {
9 val catalogs = extensions.getByType(VersionCatalogsExtension::class.java)
10 return catalogs.named("libs")
11 }

You can see that we've pulled a lot of the repeated configuration code we normally write in our Gradle files and put them inside these reusable functions. The final piece to the puzzle is just declaring the `id("android-library-convention")` plugin like we did in the above example:

1plugins {
2 id("android-library-convention")
3}
4
5android {
6 namespace = "com.example.myexamplelibrary"
7}
8
9dependencies {
10 ...any extra dependencies needed for this module
11}

You can be flexible and move as much as you want into these convention plugins or just make them smaller so you can reuse configuration setup for things such as the `compile-sdk` across modules to avoid manually creating each individual module.

Here is an example of a hilt convention plugin:

1import ext.libs
2
3plugins {
4 id("com.google.devtools.ksp")
5 id("dagger.hilt.android.plugin")
6}
7
8dependencies {
9 "implementation"(libs.findLibrary("hilt").get())
10 "ksp"(libs.findLibrary("hilt.android.compiler").get())
11 "implementation"(libs.findLibrary("hilt.viewmodel").get())
12}

Now, any module that imports this plugin no longer needs to manually specify hilt plugins or hilt dependencies. This convention plugin will do that simply by importing it.

The final build-logic folder should look something like this:

Screenshot of Android modular project conventions in Android Studio

Final thoughts

Convention plugins take a small effort up front to put in place. But once your project supports them, they make creating additional modules a breeze and they are easier to maintain if you're a feature developer looking to add dependencies.

Check out the NowInAndroid project as it includes convention plugins and is a great reference of modern Android best practices.