Skip to content

Instantly share code, notes, and snippets.

@hasancse91
Last active December 23, 2023 06:47
Show Gist options
  • Save hasancse91/010aa1b170856e5b7cfe2a6ecc7ddf82 to your computer and use it in GitHub Desktop.
Save hasancse91/010aa1b170856e5b7cfe2a6ecc7ddf82 to your computer and use it in GitHub Desktop.
This is a sample Gist of Download utility class for Dynamic Feature Module Delivery. Full repository: https://github.com/hasancse91/dynamic-feature-module-android
const val TAG = "dynamic_module_util"
interface DynamicDeliveryCallback {
fun onDownloading()
fun onDownloadCompleted()
fun onInstallSuccess()
fun onFailed(errorMessage: String)
}
class DynamicModuleDownloadUtil(context: Context, private val callback: DynamicDeliveryCallback) {
private lateinit var splitInstallManager: SplitInstallManager
private var mySessionId = 0
init {
if (!::splitInstallManager.isInitialized) {
splitInstallManager = SplitInstallManagerFactory.create(context)
}
}
fun isModuleDownloaded(moduleName: String): Boolean {
return splitInstallManager.installedModules.contains(moduleName)
}
fun downloadDynamicModule(moduleName: String) {
val request = SplitInstallRequest.newBuilder()
.addModule(moduleName)
.build()
val listener = SplitInstallStateUpdatedListener { state -> handleInstallStates(state) }
splitInstallManager.registerListener(listener)
splitInstallManager.startInstall(request)
.addOnSuccessListener { sessionId ->
mySessionId = sessionId
}
.addOnFailureListener { e ->
Log.d(TAG, "Exception: $e")
handleInstallFailure((e as SplitInstallException).errorCode)
}
splitInstallManager.unregisterListener(listener)
}
private fun handleInstallFailure(errorCode: Int) {
when (errorCode) {
SplitInstallErrorCode.NETWORK_ERROR -> {
callback.onFailed("No internet found")
}
SplitInstallErrorCode.MODULE_UNAVAILABLE -> {
callback.onFailed("Module unavailable")
}
SplitInstallErrorCode.ACTIVE_SESSIONS_LIMIT_EXCEEDED -> {
callback.onFailed("Active session limit exceeded")
}
SplitInstallErrorCode.INSUFFICIENT_STORAGE -> {
callback.onFailed("Insufficient storage")
}
SplitInstallErrorCode.PLAY_STORE_NOT_FOUND -> {
callback.onFailed("Google Play Store Not Found!")
}
else -> {
callback.onFailed("Something went wrong! Try again later")
}
}
}
private fun handleInstallStates(state: SplitInstallSessionState) {
if (state.sessionId() == mySessionId) {
when (state.status()) {
SplitInstallSessionStatus.DOWNLOADING -> {
callback.onDownloading()
}
SplitInstallSessionStatus.DOWNLOADED -> {
callback.onDownloadCompleted()
}
SplitInstallSessionStatus.INSTALLED -> {
Log.d(TAG, "Dynamic Module downloaded")
callback.onInstallSuccess()
}
SplitInstallSessionStatus.FAILED -> {
callback.onFailed("Installation failed")
}
SplitInstallSessionStatus.CANCELED -> {
callback.onFailed("Installation Cancelled")
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment