git.iko.soy/opencode-android
on aeac232 help sign in
59 lines 2.1 kB history raw
1package soy.iko.opencode
3import android.app.Application
4import coil.ImageLoader
5import coil.ImageLoaderFactory
6import coil.disk.DiskCache
7import coil.memory.MemoryCache
8import soy.iko.opencode.data.repo.CrashLogger
9import soy.iko.opencode.di.AppContainer
10import java.util.concurrent.atomic.AtomicBoolean
12class OpencodeApp : Application(), ImageLoaderFactory {
13 lateinit var container: AppContainer
14 private set
16 private val shutdownCalled = AtomicBoolean(false)
18 override fun onCreate() {
19 super.onCreate()
20 CrashLogger.get(this).install()
21 container = AppContainer(this)
22 // onTerminate() is only called in emulated process environments, not on real
23 // devices. Register a JVM shutdown hook so cleanup (network callback unregister,
24 // scope cancellation, connection close) runs when the process is actually killed.
25 Runtime.getRuntime().addShutdownHook(Thread {
26 shutdown()
27 })
28 }
30 // Process-wide Coil singleton. The defaults are sane; the explicit factory adds a
31 // disk cache so scrolling back to an image-bearing message doesn't re-fetch it over
32 // the (auth-protected) network every time. Data-URI (base64) images skip the disk
33 // cache automatically; only resolved HTTP/S URLs are cached, keyed by URL.
34 override fun newImageLoader(): ImageLoader = ImageLoader.Builder(this)
35 .memoryCache {
36 MemoryCache.Builder(this)
37 .maxSizePercent(0.25)
38 .build()
39 }
40 .diskCache {
41 DiskCache.Builder()
42 .directory(cacheDir.resolve("image_cache"))
43 .maxSizeBytes(50L * 1024 * 1024)
44 .build()
45 }
46 .build()
48 override fun onTerminate() {
49 super.onTerminate()
50 shutdown()
51 }
53 private fun shutdown() {
54 // Guard against double shutdown — onTerminate and the shutdown hook can both
55 // fire in emulated environments.
56 if (!shutdownCalled.compareAndSet(false, true)) return
57 container.shutdown()
58 }