package moe.yuuta.workmode.update import android.content.Context import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent import moe.yuuta.workmode.BuildConfig import moe.yuuta.workmode.async.Async import moe.yuuta.workmode.async.Callback import moe.yuuta.workmode.async.Stoppable class LifecycleUpdateChecker(val context: Context, val callback: moe.yuuta.workmode.update.Callback) : LifecycleObserver { private lateinit var mStoppable: Stoppable @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun onCreate() { mStoppable = Async.beginTask(UpdateChecker(), object : Callback { override fun onStop(success: Boolean, result: Update?, e: Throwable?) { if (result == null) return if (result.version <= BuildConfig.VERSION_CODE) return if (!shouldOpenGooglePlay() && !result.altUrlEnabled && !result.altUrlForce) return val url = if (shouldOpenGooglePlay() && !result.altUrlForce) "https://play.google.com/store/apps/details?id=${BuildConfig.APPLICATION_ID}" else result.altUrl this@LifecycleUpdateChecker.callback.showToast(result.name, url) } private fun shouldOpenGooglePlay(): Boolean = "com.android.vending" == this@LifecycleUpdateChecker.context.packageManager.getInstallerPackageName(BuildConfig.APPLICATION_ID) }) } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun onDestroy() { if (::mStoppable.isInitialized) { mStoppable.stop() } } } @FunctionalInterface interface Callback { fun showToast(name: String, url: String) }