DEV Community

myougaTheAxo
myougaTheAxo

Posted on • Originally published at zenn.dev

Dynamic Feature Module - On-Demand Delivery Guide

Dynamic Feature Module - On-Demand Delivery Guide

Reduce initial app size by delivering features on-demand using Google Play's dynamic feature modules.

Module Setup

Create a dynamic feature module in build.gradle.kts:

plugins {
    id("com.android.dynamic-feature")
    id("kotlin-android")
}

android {
    namespace = "com.example.dynamicfeature"
    compileSdk = 34
}

dependencies {
    implementation(project(":app"))
    implementation(libs.bundles.compose)
}
Enter fullscreen mode Exit fullscreen mode

In AndroidManifest.xml:

<manifest>
    <dist:module
        dist:instant="false"
        dist:onDemand="true"
        dist:fusing dist:fusionPolicy="never">
        <application>
            <activity android:name=".DynamicFeatureActivity" />
        </application>
    </dist:module>
</manifest>
Enter fullscreen mode Exit fullscreen mode

Base Module Integration

In app's build.gradle.kts:

dynamicFeatures = [":dynamicfeature"]
Enter fullscreen mode Exit fullscreen mode

In AndroidManifest.xml:

<uses-permission android:name="com.google.android.finsky.permission.BIND_GET_INSTALL_STATE" />
Enter fullscreen mode Exit fullscreen mode

Request Installation

class DynamicFeatureViewModel(private val splitInstallManager: SplitInstallManager) : ViewModel() {
    fun requestFeatureInstall(featureName: String) {
        val request = SplitInstallRequest.newBuilder()
            .addModule(featureName)
            .build()

        splitInstallManager.startInstall(request)
            .addOnSuccessListener { sessionId ->
                // Installation started
            }
            .addOnFailureListener {
                // Handle error
            }
    }
}
Enter fullscreen mode Exit fullscreen mode

Monitor Installation State

splitInstallManager.registerListener { state ->
    when (state.status) {
        SplitInstallSessionStatus.INSTALLED -> {
            // Feature ready to use
        }
        SplitInstallSessionStatus.DOWNLOADING -> {
            // Show download progress
        }
        SplitInstallSessionStatus.FAILED -> {
            // Handle installation failure
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Launch Dynamic Feature Activity

fun launchDynamicFeature(context: Context) {
    val intent = Intent().apply {
        action = "com.example.ACTION_DYNAMIC_FEATURE"
        `package` = context.packageName
    }
    context.startActivity(intent)
}
Enter fullscreen mode Exit fullscreen mode

Best Practices

  • Use on-demand for non-critical features
  • Monitor storage space before requesting
  • Handle installation failures gracefully
  • Provide feedback during download

8 Android app templates on Gumroad

Top comments (0)