Search code examples
androidgradleandroid-gradle-plugindynamic-feature-module

How to access Android's "dynamicFeatures" property from a custom Gradle plugin in buildSrc


In my project, I'd like to generate a class that contains information about my dynamic features. Dynamic features are added this way:

// In the base module’s build.gradle file.
android {
    ...
    // Specifies dynamic feature modules that have a dependency on
    // this base module.
    dynamicFeatures = [":dynamic_feature", ":dynamic_feature2"]
}

Source: https://developer.android.com/guide/app-bundle/at-install-delivery#base_feature_relationship

I've been searching for solutions since a few days now, and I didn't find much. Currently, my plugin looks like this:

class MyPlugin : Plugin<Project> {

    override fun apply(project: Project) {
        if (project == rootProject) {
            throw Exception("This plugin cannot be applied to root project")
        }

        val parent = project.parent ?: throw Exception("Parent of project cannot be null")

        val extension = project.extensions.getByName("android") as BaseAppModuleExtension?
            ?: throw Exception("Android extension cannot be null")

        extension.dynamicFeatures
    }
}

Unfortunately, extension.dynamicFeatures is empty even if my plugin is applied to the build.gradle file having dynamic features.


Solution

  • It's empty, because you are trying to get extension value at the gradle lifecycle configuration stage, all gradle properties have not configured yet.

    Use afterEvaluate closure. In this block dynamicFeatures has already configured and not empty.

    project.afterEvaluate {
        val extension = project.extensions.getByType(BaseAppModuleExtension::class.java)
            ?: throw Exception("Android extension cannot be null")
        extension.dynamicFeatures
    }