DEV Community

Victor Rattis
Victor Rattis

Posted on

2 2

Tip: How to avoid duplicating Gradle codes in Multi Android modules

Let's assume the following code is added in more than one Android Gradle module on a project which has multiple Gradle modules.

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 30
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }
}
Enter fullscreen mode Exit fullscreen mode

To avoid duplicating this code in more than one module Gradle and avoid making mistakes, you could use the following solution:

Create a Gradle Script file in the root project, and for this code, you could create for example android.gradle and add the code common in it:

android {
    compileSdkVersion 30
    buildToolsVersion "30.0.3"

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 30
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = '1.8'
    }
}
Enter fullscreen mode Exit fullscreen mode

and in build.gradle of each Gradle module you can include it using apply from:'../android.gradle'. For example, including it into app/build.gradle.

apply from:'../android.gradle'

android {
    defaultConfig {
        applicationId "com.my.application"
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs