aboutsummaryrefslogtreecommitdiff
path: root/app/src/main/java/moe/yuuta/workmode/update/LifecycleUpdateChecker.kt
blob: 9e2cd89d4378650eb8a38018344091473018d64b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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<Update> {
            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)
}