Conditional dependencies with Gradle, is it possible?

前端 未结 3 1160
醉话见心
醉话见心 2021-01-12 21:41

I have an Android project (already ported to Android Studio and using Gradle) that is made up of different modules.

The project is actually used to create two differ

相关标签:
3条回答
  • 2021-01-12 21:50

    Since you already have the product flavors:

    productFlavors {
        producta {
        }
    
        productb {
        }
    }
    

    Define your dependencies prefixed with flavor name. Example:

    dependencies {
        productaImplementation 'com.google.android.gms:play-services:11.0.2'
        productbImplementation 'com.google.android.gms:play-services:12.0.1'
    }
    

    Common dependencies will be defined normally.

    Now build apk for individual flavors.

    0 讨论(0)
  • 2021-01-12 21:55

    Not the best way to do it, but if productFlavors is not enough to specify conditional dependencies you can rely on an inline if and evaluate it based on some value that can be injected via external properties.

    For example here is how I toggle LeakCanary (no-op is just the empty implementation of the other one):

    build.gradle

    dependencies {
        compile "com.squareup.leakcanary:leakcanary-android"+(project.ext.has("leakCanary")?"":"-no-op")+":1.3.1"
    }
    

    To build with com.squareup.leakcanary:leakcanary-android:1.3.1:

    $ ./gradlew :app:assembleDebug -PleakCanary
    

    By default it builds with the empty implementation com.squareup.leakcanary:leakcanary-android-no-op:1.3.1:

    $ ./gradlew :app:assembleDebug
    

    This provides a quick and more flexible way to toggle things using build command, but too much of it and things will get messy real quick.

    0 讨论(0)
  • 2021-01-12 22:13

    Yes, it is. New Android build system based on Gradle supports your use case with its concept of product flavors. http://tools.android.com/tech-docs/new-build-system/user-guide

    Note that you will likely want to switch from Eclipse to Android Studio when you do migration to Gradle build.

    0 讨论(0)
提交回复
热议问题