Skip to content

prongbang/inapp-update

Repository files navigation

inapp-update

In-app updates wrapper for Android, Supported Java 11.

Setup

  • build.gradle
buildscript {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}
  • settings.gradle
dependencyResolutionManagement {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}
  • app/build.gradle
implementation 'com.github.prongbang:inapp-update:1.0.1'

How to use

import com.google.android.play.core.install.model.AppUpdateType
import com.prongbang.appupdate.AppUpdateInstallerListener
import com.prongbang.appupdate.AppUpdateInstallerManager
import com.prongbang.appupdate.InAppUpdateInstallerManager

class SplashActivity : AppCompatActivity() {

    private val appUpdateInstallerManager: AppUpdateInstallerManager by lazy {
        InAppUpdateInstallerManager(this)
    }

    private val appUpdateInstallerListener by lazy {
        object : AppUpdateInstallerListener() {
            // On downloaded but not installed.
            override fun onDownloadedButNotInstalled() = popupSnackBarForCompleteUpdate()

            // On failure
            override fun onFailure(e: Exception) = navigateToMain()

            // On not update
            override fun onNotUpdate() = navigateToMain()

            // On cancelled update
            override fun onCancelled() = navigateToMain()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        appUpdateInstallerManager.addAppUpdateListener(appUpdateInstallerListener)
        appUpdateInstallerManager.startCheckUpdate()
    }

    override fun onResume() {
        super.onResume()
        appUpdateInstallerManager.resumeCheckUpdate(AppUpdateType.FLEXIBLE)
        // or
        // appUpdateInstallerManager.resumeCheckUpdate(AppUpdateType.IMMEDIATE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        appUpdateInstallerManager.onActivityResult(requestCode, resultCode, data)
    }

    private fun navigateToMain() {
        startActivity(Intent(this, MainActivity::class.java))
        finishAffinity()
    }

    private fun popupSnackBarForCompleteUpdate() {
        val snackBar = Snackbar.make(
            findViewById(android.R.id.content),
            "An update has just been downloaded.",
            Snackbar.LENGTH_INDEFINITE
        )
        snackBar.setAction("RESTART") { appUpdateInstallerManager.completeUpdate() }
        snackBar.setActionTextColor(ContextCompat.getColor(this, android.R.color.holo_red_dark))
        snackBar.show()
    }
}