Created
April 25, 2022 15:21
-
-
Save johnkil/8b860eb80d2ccece5f75731ccd453c74 to your computer and use it in GitHub Desktop.
Support in-app updates
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private fun initAppUpdateFlow() { | |
logcat { "check app update" } | |
val appUpdateManager = AppUpdateManagerFactory.create(this) | |
lifecycleScope.launch { | |
try { | |
appUpdateManager.requestUpdateFlow().collect(::onAppUpdateResult) | |
} catch (e: InstallException) { | |
logcat(LogPriority.ERROR) { "Failed to request app update flow\n${e.asLog()}" } | |
} | |
} | |
} | |
private fun onAppUpdateResult(result: AppUpdateResult) { | |
when (result) { | |
AppUpdateResult.NotAvailable -> onAppUpdateNotAvailable() | |
is AppUpdateResult.Available -> onAppUpdateAvailable(result) | |
is AppUpdateResult.InProgress -> onAppUpdateInProgress(result) | |
is AppUpdateResult.Downloaded -> onAppUpdateDownloaded(result) | |
} | |
} | |
private fun onAppUpdateNotAvailable() { | |
logcat { "App update not available" } | |
} | |
private fun onAppUpdateAvailable(result: AppUpdateResult.Available) { | |
logcat { "App update available ${result.updateInfo.availableVersionCode()}" } | |
val availableVersionCode = result.updateInfo.availableVersionCode() | |
val currentVersionCode = BuildConfig.VERSION_CODE | |
val isMajorUpdate = availableVersionCode - currentVersionCode >= 1000000 | |
if (isMajorUpdate && result.updateInfo.isImmediateUpdateAllowed) { | |
result.startImmediateUpdate(this, REQUEST_CODE_APP_UPDATE_IMMEDIATE) | |
return | |
} | |
val isMinorUpdate = availableVersionCode - currentVersionCode >= 10000 | |
if (isMinorUpdate && result.updateInfo.isFlexibleUpdateAllowed) { | |
result.startFlexibleUpdate(this, REQUEST_CODE_APP_UPDATE_FLEXIBLE) | |
return | |
} | |
logcat { "Skip app update $availableVersionCode" } | |
} | |
private fun onAppUpdateInProgress(result: AppUpdateResult.InProgress) { | |
val progress = result.installState.run { bytesDownloaded() * 100 / totalBytesToDownload() } | |
logcat { "App update in progress $progress" } | |
} | |
private fun onAppUpdateDownloaded(result: AppUpdateResult.Downloaded) { | |
logcat { "App update downloaded" } | |
Snackbar.make( | |
findViewById(android.R.id.content), | |
R.string.app_update_downloaded, | |
Snackbar.LENGTH_INDEFINITE | |
).apply { | |
setAction(R.string.app_update_complete_update) { | |
lifecycleScope.launch { result.completeUpdate() } | |
} | |
}.show() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment