AppIconService.android.kt
composeApp/src/androidMain/kotlin/eu/friedcutlet/yokan/services/appicons/AppIconService.android.kt
1package eu.friedcutlet.yokan.services.appicons23import android.content.ComponentName4import android.content.pm.PackageManager5import android.os.Build6import eu.friedcutlet.yokan.AndroidAppContext7import kotlinx.coroutines.Dispatchers8import kotlinx.coroutines.sync.Mutex9import kotlinx.coroutines.sync.withLock10import kotlinx.coroutines.withContext1112actual fun createPlatformAppIconService(): AppIconService = AndroidAppIconService()1314private class AndroidAppIconService : AppIconService {15 override val capabilities = AppIconCapabilities(AppIconPlatform.Android, ExplicitAppIcons)16 private val mutex = Mutex()17 private val context get() = checkNotNull(AndroidAppContext.appContext) { "Android context unavailable" }18 private val manager get() = context.packageManager19 // Stable names must be retained across upgrades; never disable the deep-link target activity.20 private fun component(selection: AppIconSelection) = ComponentName(context, when (selection) {21 AppIconSelection.Default -> "eu.friedcutlet.yokan.LauncherDefault"22 ExplicitAppIcons[1] -> "eu.friedcutlet.yokan.LauncherToriiLight"23 ExplicitAppIcons[2] -> "eu.friedcutlet.yokan.LauncherToriiDark"24 else -> error("Unsupported icon")25 })26 private fun enabled(selection: AppIconSelection): Boolean = when (manager.getComponentEnabledSetting(component(selection))) {27 PackageManager.COMPONENT_ENABLED_STATE_DEFAULT -> selection == AppIconSelection.Default28 PackageManager.COMPONENT_ENABLED_STATE_ENABLED -> true29 else -> false30 }31 override suspend fun current(): AppIconSelection? = withContext(Dispatchers.IO) {32 mutex.withLock { ExplicitAppIcons.filter(::enabled).singleOrNull() }33 }34 override suspend fun apply(selection: AppIconSelection) = withContext(Dispatchers.IO) {35 require(selection in capabilities.choices)36 mutex.withLock {37 if (Build.VERSION.SDK_INT >= 33) {38 manager.setComponentEnabledSettings(ExplicitAppIcons.map { icon ->39 PackageManager.ComponentEnabledSetting(component(icon),40 if (icon == selection) PackageManager.COMPONENT_ENABLED_STATE_ENABLED41 else PackageManager.COMPONENT_ENABLED_STATE_DISABLED,42 PackageManager.DONT_KILL_APP)43 })44 } else {45 // Older OS versions have no atomic batch. Enable the destination first so a46 // failure can leave duplicate icons, but never an installation without a launcher.47 manager.setComponentEnabledSetting(component(selection), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP)48 ExplicitAppIcons.filter { it != selection }.forEach { icon ->49 manager.setComponentEnabledSetting(component(icon), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP)50 }51 }52 check(ExplicitAppIcons.filter(::enabled).singleOrNull() == selection)53 }54 }55}56