diff --git a/docs/kill-app-options.md b/docs/kill-app-options.md new file mode 100644 index 0000000000..d3fc6c5e5f --- /dev/null +++ b/docs/kill-app-options.md @@ -0,0 +1,174 @@ +# Killing app options + +`Settings -> Backup settings -> Killing app options` decides what happens to an app right before +its data is read (backup) or written (restore). The very same list is shown under +`Settings -> Restore settings`, and both pages read and write the same preference, so a single +choice applies to backups and restores alike. + +* Preference key: `kill_app_option` in DataStore (`KeyKillAppOption`), holding the name of + `com.xayah.core.model.KillAppOption`. +* Read once per task in `AbstractBackupService.onProcessing()` / `AbstractRestoreService.onProcessing()`, + then applied per package with `AbstractPackagesService.killApp()`. +* When option III is active, the suspension is lifted again by `releaseApp()` once the package has + been processed. +* Stopping and suspending a package is a **best-effort helper** of the task: a failure in any of those + steps – including the user trying to open the app in the meantime – only writes a log line, it never + aborts the task and never fails the package. See + [Opening the app while it is being backed up](#opening-the-app-while-it-is-being-backed-up). + +| Option | Enum | Mechanism | Runs as | +| --- | --- | --- | --- | +| Disabled | `DISABLED` | Nothing | – | +| Option One | `OPTION_I` | Root shell retry loop (`killall` / `am force-stop` / `am kill`) | root shell | +| Option II (default) | `OPTION_II` | One `IActivityManager.forceStopPackageAsUser()` call | root service (Binder) | +| Advanced pause | `OPTION_III` | `am force-stop` followed by `pm suspend` | root shell | + +## Disabled + +Only a log line is written (`Won't kill .`). The app keeps running while its data is +copied, which is the fastest option and the only one that leaves the app untouched. + +## Option One + +Implemented in `BaseUtil.killPackage()`. A new root shell (libsu) is opened, the global mount +namespace is entered (`nsenter --mount=/proc/1/ns/mnt sh`), and this loop is executed: + +```sh +until [[ $(dumpsys activity processes | grep "packageList" | cut -d '{' -f2 | cut -d '}' -f1 \ + | egrep -w "$packageName" | sed -n '1p') = "" ]]; do + killall -9 "$packageName" &>/dev/null + am force-stop --user "$userId" "$packageName" &>/dev/null + am kill "$packageName" &>/dev/null +done +``` + +* `dumpsys activity processes` lists the running processes of the package; the loop keeps going + until the package no longer appears in it. +* `killall -9` sends `SIGKILL` to every process whose name matches the package name. +* `am force-stop` asks ActivityManager to stop the package, `am kill` kills its background processes. +* The whole job is given 3 seconds (`timeout = 3`); when it expires, the command is closed and the + backup continues anyway. +* Because it is a shell loop, the package can be started again by a broadcast or a job in the middle + of the loop, which is why it has to be retried. This is the option that most often leaves the app + running while its data is copied. + +## Option II (default) + +Implemented in `AbstractPackagesService.killApp()` together with +`RemoteRootService.forceStopPackageAsUser()`: + +```kotlin +mRootService.forceStopPackageAsUser(pkg.packageEntity.packageName, pkg.packageEntity.userId) +``` + +* The call crosses Binder into the root process (`:root`, running as uid 0) and ends up in the + hidden `ActivityManager.forceStopPackageAsUser(packageName, userId)`. +* It is a single call: ActivityManager force-stops every process of the package, marks the package + as stopped and cancels its alarms/jobs, so nothing restarts it until the user launches it again. +* No shell, no retry loop, no 3 second budget – this is why it is the default. + +## Option III — Advanced pause + +Both mechanisms above only *stop* the app. An app with a foreground service, an `AlarmManager` +alarm, a `JobScheduler` job or a push channel can come back while its files are being archived. +Option III additionally **suspends** the package, which the platform honours for every start +request, and the launcher shows the icon greyed out. + +Implemented in `SuspendUtil.suspendPackage()` + `BaseUtil.suspendPackage()` (and the matching +`resumePackage()` / `resumeAll()`): + +```sh +am force-stop --user "$userId" "$packageName" +pm suspend --user "$userId" "$packageName" +``` + +```sh +pm unsuspend --user "$userId" "$packageName" +``` + +* `pm suspend` requires `android.permission.SUSPEND_APPS`, which is only granted to root/shell, so + the command is executed through the root shell (`libsu`). +* While suspended, the package cannot be started by the launcher, by broadcasts, by services, by + jobs or by other apps; its icon is greyed out and its notifications are suppressed. Reading its + files keeps working, which is exactly what a backup needs. +* The suspension is lifted by `releaseApp()` in a `finally` block right after that app has been + processed, so it lasts for the duration of **one app**, not the whole task. +* Every suspended package is written to `files/suspended_packages.txt` before the command is issued. + At the beginning of a task `releaseApps()` calls `pm unsuspend` for every entry of that file, so a + task that was killed, crashed or interrupted by a reboot cannot leave an app suspended forever. +* **System apps are never suspended.** For a package with `PackageEntity.isSystemApp == true` the + option falls back to a plain force-stop (`forceStopPackageAsUser`), because suspending + `com.android.systemui`, the launcher or another core package can take the device down. + The app never suspends itself either. + +### Verifying the state by hand + +```sh +adb shell dumpsys package | grep -i suspended # suspended=true means paused +adb shell pm unsuspend --user 0 # lift it manually +``` + +`pm suspend` exists since Android 7.0 (API 24), which matches the app's `minSdk`. + +## Opening the app while it is being backed up + +Two things have to hold **at the same time**: the app cannot be opened while it is being backed up, +and the attempt to open it does not change the outcome of the backup. Three layers take care of that. + +### 1. It does not open, because the package is suspended + +After `pm suspend`, the platform refuses every start request – `am start` answers +`Activity not started`, a tap on the launcher does nothing and the icon is greyed out. This was +verified against a control group on an emulator (android-33 x86_64): + +| State | Result of one `am start` | Does the app record a launch | +| --- | --- | --- | +| Not suspended | `pid: 20094`, process created | yes | +| Suspended | `pid: (none)`, no process | no | + +### 2. The attempt does not fail the backup: `tar` exit code 1 is accepted + +Before the suspension lands – or right after the system lifted it on its own – the app may already +be running. Reading its data then hits "a file changed while it was being read", and `tar` exits +with code **1** (`file changed as we read it`). The archive is still perfectly readable, but +`ShellResult.isSuccess` used to accept only 0, so the package was reported as failed. + +`PackagesBackupUtil.isAcceptableTarResult()` changes the verdict to: + +| Exit code | Meaning | Outcome | +| --- | --- | --- | +| 0 | Finished normally | pass | +| 1 | Some files changed or vanished while being read | **pass**, `testArchive()` is the verdict | +| 2 | Fatal error | fail | +| anything else / no result / timeout | Command broke | fail | + +In other words, whether the archive can be decompressed and listed is what decides, not whether +somebody touched the files. + +### 3. Started in between: `reinforcePause()` pauses it again + +`killApp()` runs once per package, but reading the data takes several passes (APK, user data, +device-protected data, app data). To close the window where the APK pass is done and the app is +already up again by the time the data is read, the pause is re-applied in between: + +``` +backup(APK) -> reinforcePause() -> backup(USER) -> backup(USER_DE) -> reinforcePause() -> backup(DATA) -> ... +``` + +A restore has the same window: installing the APK may start the app, so `reinforcePause()` is called +again before `PACKAGE_DATA` is written. It only does something for option III and for non-system +packages, and running it repeatedly is safe (`pm suspend` on an already suspended package is a no-op). + +### 4. No failure along the way can drag the task down + +`killApp()` / `releaseApp()` / `releaseApps()` / `SuspendUtil` / `BaseUtil.suspendPackage()` are all +wrapped in `runCatching` and only log the failure: + +``` +Failed to pause : ... +Failed to re-apply the pause of : ... +``` + +`SuspendUtil` itself runs on `Dispatchers.IO + NonCancellable`, so a cancelled task still lifts every +suspension it applied and never leaves an app greyed out. + diff --git a/docs/kill-app-options.zh-CN.md b/docs/kill-app-options.zh-CN.md new file mode 100644 index 0000000000..05e00bb919 --- /dev/null +++ b/docs/kill-app-options.zh-CN.md @@ -0,0 +1,156 @@ +# 杀死应用选项(实现说明) + +`设置 -> 备份设置 -> 杀死应用选项` 决定每个应用在读取数据(备份)或写入数据(恢复)之前被如何处理。 +同样的选项也会出现在 `设置 -> 恢复设置` 中,两个页面读写的是同一个偏好项,因此选择一次即对备份与恢复同时生效。 + +* 偏好项:DataStore 中的 `kill_app_option`(`KeyKillAppOption`),值为 + `com.xayah.core.model.KillAppOption` 的枚举名。 +* 每个任务开始时读取一次:`AbstractBackupService.onProcessing()` / + `AbstractRestoreService.onProcessing()`,随后按应用逐个调用 `AbstractPackagesService.killApp()`。 +* 选中「高级暂停」时,应用处理结束后由 `releaseApp()` 解除挂起。 +* 停止/挂起应用都只是任务里的**尽力而为的辅助步骤**:任何一步失败(包括用户在此期间尝试打开应用) + 只写日志,不会中止任务,也不会把该应用判定为备份失败。详见 + [备份过程中尝试打开被备份的应用](#备份过程中尝试打开被备份的应用)。 + +| 选项 | 枚举 | 实现方式 | 执行身份 | +| --- | --- | --- | --- | +| 禁用 | `DISABLED` | 不做任何处理 | – | +| 方案I | `OPTION_I` | root shell 循环重试(`killall` / `am force-stop` / `am kill`) | root shell | +| 方案II(默认) | `OPTION_II` | 调用一次 `IActivityManager.forceStopPackageAsUser()` | root 服务(Binder)| +| 高级暂停 | `OPTION_III` | 先 `am force-stop`,再 `pm suspend` | root shell | + +## 禁用 + +只写一行日志(`Won't kill <包名>.`),应用在数据复制期间保持运行。速度最快,也是唯一完全不干扰应用的选项。 + +## 方案I + +实现在 `BaseUtil.killPackage()`。先通过 libsu 新开一个 root shell,切入全局挂载命名空间 +(`nsenter --mount=/proc/1/ns/mnt sh`),再执行下面的循环: + +```sh +until [[ $(dumpsys activity processes | grep "packageList" | cut -d '{' -f2 | cut -d '}' -f1 \ + | egrep -w "$packageName" | sed -n '1p') = "" ]]; do + killall -9 "$packageName" &>/dev/null + am force-stop --user "$userId" "$packageName" &>/dev/null + am kill "$packageName" &>/dev/null +done +``` + +* 用 `dumpsys activity processes` 判断该包是否还在进程列表中,只要还在就一直循环。 +* `killall -9` 向所有同名的进程发送 `SIGKILL`。 +* `am force-stop` 请求 ActivityManager 停止该包,`am kill` 杀掉其后台进程。 +* 整体给 3 秒(`timeout = 3`),超时后关闭命令、照常继续备份。 +* 因为只是一个 shell 循环,循环过程中应用仍可能被广播或任务重新拉起,所以才需要反复重试。 + 这也是最容易出现「备份时应用仍在运行」的选项。 + +## 方案II(默认) + +实现在 `AbstractPackagesService.killApp()` 与 `RemoteRootService.forceStopPackageAsUser()`: + +```kotlin +mRootService.forceStopPackageAsUser(pkg.packageEntity.packageName, pkg.packageEntity.userId) +``` + +* 经由 Binder 进入 root 进程(`:root`,uid 0),最终调用隐藏 API + `ActivityManager.forceStopPackageAsUser(packageName, userId)`。 +* 只有一次调用:ActivityManager 停止该包的全部进程、把包标记为 stopped,并取消其闹钟与任务, + 在用户主动点开之前不会被重新拉起。 +* 不需要 shell、没有重试循环、也没有 3 秒限制,因此是默认值。 + +## 高级暂停(方案III) + +前两个方案只是「停掉」应用。带有前台服务、`AlarmManager` 闹钟、`JobScheduler` 任务或推送通道的应用, +完全可以在文件被打包的过程中重新起来。方案III 在此基础上把包**挂起(suspend)**, +系统会拦截所有启动请求,同时桌面图标变灰。 + +实现在 `SuspendUtil.suspendPackage()` + `BaseUtil.suspendPackage()`(以及配套的 +`resumePackage()` / `resumeAll()`): + +```sh +am force-stop --user "$userId" "$packageName" +pm suspend --user "$userId" "$packageName" +``` + +```sh +pm unsuspend --user "$userId" "$packageName" +``` + +* `pm suspend` 需要 `android.permission.SUSPEND_APPS`,该权限只授予 root/shell,因此命令通过 root shell 执行。 +* 挂起期间:桌面、广播、服务、任务栏、其他应用都无法拉起它;图标变灰、通知被抑制; + 但读取其文件不受影响,这正是备份需要的效果。 +* 解除挂起放在 `finally` 里的 `releaseApp()`,即该应用处理完立即解除——作用范围是**单个应用**, + 而不是整个任务。 +* 挂起前会先把 `uid:包名` 写入 `files/suspended_packages.txt`;任务开始时 `releaseApps()` 会对文件中 + 的每一项执行 `pm unsuspend`。因此即使任务被强杀、崩溃或中途重启,也不会让某个应用永远处于挂起状态。 +* **系统应用绝不挂起。** `PackageEntity.isSystemApp == true` 的包会退化为直接强制停止 + (`forceStopPackageAsUser`)——挂起 `com.android.systemui`、桌面或其它核心包可能直接让设备不可用。 + 应用本身也不会挂起自己。 + +### 手动验证状态 + +```sh +adb shell dumpsys package <包名> | grep -i suspended # suspended=true 表示处于挂起 +adb shell pm unsuspend --user 0 <包名> # 手动解除 +``` + +`pm suspend` 自 Android 7.0(API 24)起提供,与本应用的 `minSdk` 一致。 + +## 备份过程中尝试打开被备份的应用 + +目标语义是两条**同时**成立:备份期间被备份的应用打不开;而用户「尝试打开」这个动作本身 +**不影响备份结果**。实现上分三层保障。 + +### 1. 打不开由挂起保证 + +`pm suspend` 之后,任何启动请求都会被系统拒绝——`am start` 返回 +`Activity not started`,桌面点击无反应,图标变灰。这一点在模拟器(android-33 x86_64)上做过对照验证: + +| 场景 | 一次 `am start` 的结果 | 应用是否写入启动记录 | +| --- | --- | --- | +| 未挂起 | `pid: 20094`,进程拉起 | 写入 | +| 已挂起 | `pid: (none)`,进程未创建 | 不写入 | + +### 2. 「尝试打开」不导致失败:`tar` 退出码 1 视为可接受 + +挂起之前,或者挂起被系统自动解除的瞬间,应用可能已经在运行。这时读它的数据会出现 +「读的时候文件变了」,`tar` 会以退出码 **1** 结束(`file changed as we read it`)。 +归档本身仍然完整可读,但在旧逻辑里 `ShellResult.isSuccess` 只认 0,于是整包被判失败。 + +`PackagesBackupUtil.isAcceptableTarResult()` 把判定改为: + +| 退出码 | 含义 | 处理 | +| --- | --- | --- | +| 0 | 正常结束 | 通过 | +| 1 | 有文件在读取过程中变化/消失 | **通过**,以 `testArchive()` 的解压校验为准 | +| 2 | 致命错误 | 失败 | +| 其它 / 缺少结果 / 超时 | 命令异常 | 失败 | + +也就是说,真正决定成败的是 `testArchive()` 能否正常解压并列出归档内容,而不是「有没有人动过文件」。 + +### 3. 处理中途被拉起:`reinforcePause()` 重新挂起 + +`killApp()` 只在每个应用开始时执行一次,而读数据分成 APK、用户数据(DE)、应用数据等多趟。 +为了不留下「APK 读完了、数据开始读的时候应用已经起来了」这个窗口,读完前两趟之后会再挂起一次: + +``` +backup(APK) -> reinforcePause() -> backup(USER) -> backup(USER_DE) -> reinforcePause() -> backup(DATA) -> ... +``` + +恢复同理:安装完 APK 之后系统可能把应用拉起来,因此在写 `PACKAGE_DATA` 之前也调一次 +`reinforcePause()`。只有在「高级暂停」且非系统应用时才会真正执行,重复执行是安全的 +(`pm suspend` 对已挂起的包再次执行不会报错)。 + +### 4. 任何一步出错都不拖垮任务 + +`killApp()` / `releaseApp()` / `releaseApps()` / `SuspendUtil` / `BaseUtil.suspendPackage()` +全部用 `runCatching` 包住,失败只写一条日志: + +``` +Failed to pause <包名>: ... +Failed to re-apply the pause of <包名>: ... +``` + +`SuspendUtil` 内部跑在 `Dispatchers.IO + NonCancellable` 上,所以即使任务被取消, +该解除的挂起仍然会被解除,不会把应用留在灰掉的状态。 + diff --git a/source/app/src/main/res/values-zh-rCN/strings.xml b/source/app/src/main/res/values-zh-rCN/strings.xml index 262a563c21..9ac54b1672 100644 --- a/source/app/src/main/res/values-zh-rCN/strings.xml +++ b/source/app/src/main/res/values-zh-rCN/strings.xml @@ -339,9 +339,14 @@ 请勿选择根目录 方案I 方案II + 高级暂停 禁用 杀死应用选项 备份应用前行为 + 不做任何处理,应用在数据复制期间保持运行。 + 在 root shell 中循环执行 killall -9、am force-stop 与 am kill,直到该应用从 dumpsys activity processes 中消失;3 秒后仍未消失则放弃。 + 由 root 服务通过 Binder 调用一次 IActivityManager.forceStopPackageAsUser(),该应用的全部进程会被一次性停止。 + 先强行停止应用,再用 pm suspend 挂起:桌面、广播、服务与任务都无法再拉起它,图标随之变灰;该应用处理完成后立刻解除挂起。系统应用只会被强行停止。 语言 下载 更新日志 diff --git a/source/app/src/main/res/values-zh-rHK/strings.xml b/source/app/src/main/res/values-zh-rHK/strings.xml index 64cb74888b..a3a133ecee 100644 --- a/source/app/src/main/res/values-zh-rHK/strings.xml +++ b/source/app/src/main/res/values-zh-rHK/strings.xml @@ -337,9 +337,14 @@ 請勿選擇根目錄 方案I 方案II + 進階暫停 禁用 殺死應用選項 備份應用前行爲 + 不做任何處理,應用在資料複製期間保持執行。 + 在 root shell 中循環執行 killall -9、am force-stop 與 am kill,直到該應用從 dumpsys activity processes 中消失;3 秒後仍未消失則放棄。 + 由 root 服務透過 Binder 呼叫一次 IActivityManager.forceStopPackageAsUser(),該應用的全部行程會被一次性停止。 + 先強制停止應用,再用 pm suspend 暫停:桌面、廣播、服務與任務都無法再啟動它,圖示隨之變灰;該應用處理完成後立刻解除暫停。系統應用只會被強制停止。 語言 下載 更新日志 diff --git a/source/app/src/main/res/values-zh-rTW/strings.xml b/source/app/src/main/res/values-zh-rTW/strings.xml index 76878e360c..6dda32cca4 100644 --- a/source/app/src/main/res/values-zh-rTW/strings.xml +++ b/source/app/src/main/res/values-zh-rTW/strings.xml @@ -337,9 +337,14 @@ 請勿選擇根目錄 Option One Option II + 進階暫停 禁用 殺死應用選項 備份應用前行爲 + 不做任何處理,應用在資料複製期間保持執行。 + 在 root shell 中循環執行 killall -9、am force-stop 與 am kill,直到該應用從 dumpsys activity processes 中消失;3 秒後仍未消失則放棄。 + 由 root 服務透過 Binder 呼叫一次 IActivityManager.forceStopPackageAsUser(),該應用的全部行程會被一次性停止。 + 先強制停止應用,再用 pm suspend 暫停:桌面、廣播、服務與任務都無法再啟動它,圖示隨之變灰;該應用處理完成後立刻解除暫停。系統應用只會被強制停止。 語言 下載 更新日志 diff --git a/source/app/src/main/res/values/arrays.xml b/source/app/src/main/res/values/arrays.xml index 9ea946ad53..458facac5f 100644 --- a/source/app/src/main/res/values/arrays.xml +++ b/source/app/src/main/res/values/arrays.xml @@ -30,5 +30,6 @@ @string/disabled @string/option_i @string/option_ii + @string/option_iii \ No newline at end of file diff --git a/source/app/src/main/res/values/strings.xml b/source/app/src/main/res/values/strings.xml index fedaadd350..0d931651a5 100644 --- a/source/app/src/main/res/values/strings.xml +++ b/source/app/src/main/res/values/strings.xml @@ -350,9 +350,14 @@ Please do not select the root directory Option One Option II + Advanced pause Disabled Killing app options Behavior before backup + Nothing is done. The app keeps running while its data is being copied. + Root shell loop: killall -9, am force-stop and am kill are repeated until the package is gone from dumpsys activity processes. Gives up after 3 seconds. + A single IActivityManager.forceStopPackageAsUser() call made by the root service over Binder, so every process of the package is stopped at once. + Force-stops the app and then suspends it with pm suspend, so the launcher, broadcasts, services and jobs can no longer start it and its icon is greyed out. Lifted as soon as the app is processed. System apps are only force-stopped. Language Download Changelog diff --git a/source/core/model/src/main/kotlin/com/xayah/core/model/Enum.kt b/source/core/model/src/main/kotlin/com/xayah/core/model/Enum.kt index 6898d49f0e..3f3f05b8b5 100644 --- a/source/core/model/src/main/kotlin/com/xayah/core/model/Enum.kt +++ b/source/core/model/src/main/kotlin/com/xayah/core/model/Enum.kt @@ -157,7 +157,14 @@ enum class ThemeType { enum class KillAppOption { DISABLED, OPTION_I, - OPTION_II; + OPTION_II, + + /** + * Force-stops the package and suspends it with `pm suspend` until it has been processed. + * A suspended package cannot be started by the launcher, broadcasts, services or jobs, + * and its launcher icon is greyed out. + */ + OPTION_III; companion object } diff --git a/source/core/model/src/main/kotlin/com/xayah/core/model/util/ModelUtil.kt b/source/core/model/src/main/kotlin/com/xayah/core/model/util/ModelUtil.kt index 93fb1fbac1..d81eadd1c7 100644 --- a/source/core/model/src/main/kotlin/com/xayah/core/model/util/ModelUtil.kt +++ b/source/core/model/src/main/kotlin/com/xayah/core/model/util/ModelUtil.kt @@ -78,6 +78,7 @@ fun SFTPAuthMode.Companion.indexOf(index: Int): SFTPAuthMode = when (index) { fun KillAppOption.Companion.indexOf(index: Int): KillAppOption = when (index) { 1 -> KillAppOption.OPTION_I 2 -> KillAppOption.OPTION_II + 3 -> KillAppOption.OPTION_III else -> KillAppOption.DISABLED } diff --git a/source/core/service/src/main/kotlin/com/xayah/core/service/packages/AbstractPackagesService.kt b/source/core/service/src/main/kotlin/com/xayah/core/service/packages/AbstractPackagesService.kt index ef1ec4a75c..662112b2e5 100644 --- a/source/core/service/src/main/kotlin/com/xayah/core/service/packages/AbstractPackagesService.kt +++ b/source/core/service/src/main/kotlin/com/xayah/core/service/packages/AbstractPackagesService.kt @@ -10,6 +10,7 @@ import com.xayah.core.model.database.TaskDetailPackageEntity import com.xayah.core.model.util.set import com.xayah.core.service.AbstractProcessingService import com.xayah.core.service.util.PackagesBackupUtil +import com.xayah.core.util.SuspendUtil import com.xayah.core.util.command.BaseUtil internal abstract class AbstractPackagesService : AbstractProcessingService() { @@ -37,22 +38,75 @@ internal abstract class AbstractPackagesService : AbstractProcessingService() { } protected suspend fun killApp(killAppOption: KillAppOption, pkg: TaskDetailPackageEntity) = run { - // Kill the package. - when (killAppOption) { - KillAppOption.DISABLED -> { - log { "Won't kill ${pkg.packageEntity.packageName}." } - } + val packageName = pkg.packageEntity.packageName + val userId = pkg.packageEntity.userId + // Stopping the package is a best-effort helper: a failure here must not decide whether the package + // itself is backed up, and a running app must never abort the whole task. + runCatching { + when (killAppOption) { + KillAppOption.DISABLED -> { + log { "Won't kill $packageName." } + } - KillAppOption.OPTION_I -> { - log { "Trying to kill ${pkg.packageEntity.packageName}." } - BaseUtil.killPackage(context = mContext, userId = pkg.packageEntity.userId, packageName = pkg.packageEntity.packageName) - } + KillAppOption.OPTION_I -> { + log { "Trying to kill $packageName." } + BaseUtil.killPackage(context = mContext, userId = userId, packageName = packageName) + } + + KillAppOption.OPTION_II -> { + log { "Trying to kill $packageName." } + mRootService.forceStopPackageAsUser(packageName, userId) + } - KillAppOption.OPTION_II -> { - log { "Trying to kill ${pkg.packageEntity.packageName}." } - mRootService.forceStopPackageAsUser(pkg.packageEntity.packageName, pkg.packageEntity.userId) + KillAppOption.OPTION_III -> { + if (pkg.packageEntity.isSystemApp) { + // Suspending a system package can take the whole system down, so only stop it. + log { "System package $packageName is force-stopped instead of being paused." } + mRootService.forceStopPackageAsUser(packageName, userId) + } else { + log { "Trying to pause $packageName." } + val isSuccess = SuspendUtil.suspendPackage(context = mContext, userId = userId, packageName = packageName) + log { if (isSuccess) "Paused $packageName." else "Failed to pause $packageName." } + } + } } + }.onFailure { log { "Failed to kill $packageName: $it" } } + } + + /** + * Re-applies the pause of [KillAppOption.OPTION_III] right before the data is read. + * + * The suspension can be lifted behind our back: the launcher asks the user whether the app should be + * started anyway, and some ROMs resume the package on their own after a while. Re-applying the pause + * right before the data is archived means a launch attempt can neither disturb the archive nor leave a + * running process behind while its data is being read. + */ + protected suspend fun reinforcePause(killAppOption: KillAppOption, pkg: TaskDetailPackageEntity) = run { + if (killAppOption != KillAppOption.OPTION_III || pkg.packageEntity.isSystemApp) { + return@run } + runCatching { + SuspendUtil.suspendPackage(context = mContext, userId = pkg.packageEntity.userId, packageName = pkg.packageEntity.packageName) + }.onFailure { log { "Failed to re-apply the pause of ${pkg.packageEntity.packageName}: $it" } } + } + + /** + * Lifts the suspension applied by [killApp] with [KillAppOption.OPTION_III] once the package is processed. + */ + protected suspend fun releaseApp(killAppOption: KillAppOption, pkg: TaskDetailPackageEntity) = run { + if (killAppOption != KillAppOption.OPTION_III) { + return@run + } + runCatching { + SuspendUtil.resumePackage(context = mContext, userId = pkg.packageEntity.userId, packageName = pkg.packageEntity.packageName) + }.onFailure { log { "Failed to resume ${pkg.packageEntity.packageName}: $it" } } + } + + /** + * Lifts every suspension that a killed task could not lift by itself. + */ + protected suspend fun releaseApps() = run { + runCatching { SuspendUtil.resumeAll(mContext) }.onFailure { log { "Failed to resume the paused packages: $it" } } } protected abstract val mPackageDao: PackageDao diff --git a/source/core/service/src/main/kotlin/com/xayah/core/service/packages/backup/AbstractBackupService.kt b/source/core/service/src/main/kotlin/com/xayah/core/service/packages/backup/AbstractBackupService.kt index 7c7dddeaab..5b9988fcd1 100644 --- a/source/core/service/src/main/kotlin/com/xayah/core/service/packages/backup/AbstractBackupService.kt +++ b/source/core/service/src/main/kotlin/com/xayah/core/service/packages/backup/AbstractBackupService.kt @@ -141,6 +141,9 @@ internal abstract class AbstractBackupService : AbstractPackagesService() { val killAppOption = mContext.readKillAppOption().first() log { "Kill app option: $killAppOption" } + // Lift the suspensions that a previous, interrupted task could not lift by itself. + releaseApps() + mPkgEntities.forEachIndexed { index, pkg -> executeAtLeast { NotificationUtil.notify( @@ -154,50 +157,55 @@ internal abstract class AbstractBackupService : AbstractPackagesService() { log { "Current package: ${pkg.packageEntity}" } killApp(killAppOption, pkg) + try { + pkg.update(state = OperationState.PROCESSING) + val p = pkg.packageEntity + val dstDir = "${mAppsDir}/${p.archivesRelativeDir}" + var restoreEntity = mPackageDao.query(p.packageName, OpType.RESTORE, p.userId, p.preserveId, p.indexInfo.compressionType, mTaskEntity.cloud, mTaskEntity.backupDir) + mRootService.mkdirs(dstDir) + if (onAppDirCreated(archivesRelativeDir = p.archivesRelativeDir)) { + backup(type = DataType.PACKAGE_APK, p = p, r = restoreEntity, t = pkg, dstDir = dstDir) + reinforcePause(killAppOption, pkg) + backup(type = DataType.PACKAGE_USER, p = p, r = restoreEntity, t = pkg, dstDir = dstDir) + backup(type = DataType.PACKAGE_USER_DE, p = p, r = restoreEntity, t = pkg, dstDir = dstDir) + reinforcePause(killAppOption, pkg) + backup(type = DataType.PACKAGE_DATA, p = p, r = restoreEntity, t = pkg, dstDir = dstDir) + backup(type = DataType.PACKAGE_OBB, p = p, r = restoreEntity, t = pkg, dstDir = dstDir) + backup(type = DataType.PACKAGE_MEDIA, p = p, r = restoreEntity, t = pkg, dstDir = dstDir) + mPackagesBackupUtil.backupPermissions(p = p) + mPackagesBackupUtil.backupSsaid(p = p) - pkg.update(state = OperationState.PROCESSING) - val p = pkg.packageEntity - val dstDir = "${mAppsDir}/${p.archivesRelativeDir}" - var restoreEntity = mPackageDao.query(p.packageName, OpType.RESTORE, p.userId, p.preserveId, p.indexInfo.compressionType, mTaskEntity.cloud, mTaskEntity.backupDir) - mRootService.mkdirs(dstDir) - if (onAppDirCreated(archivesRelativeDir = p.archivesRelativeDir)) { - backup(type = DataType.PACKAGE_APK, p = p, r = restoreEntity, t = pkg, dstDir = dstDir) - backup(type = DataType.PACKAGE_USER, p = p, r = restoreEntity, t = pkg, dstDir = dstDir) - backup(type = DataType.PACKAGE_USER_DE, p = p, r = restoreEntity, t = pkg, dstDir = dstDir) - backup(type = DataType.PACKAGE_DATA, p = p, r = restoreEntity, t = pkg, dstDir = dstDir) - backup(type = DataType.PACKAGE_OBB, p = p, r = restoreEntity, t = pkg, dstDir = dstDir) - backup(type = DataType.PACKAGE_MEDIA, p = p, r = restoreEntity, t = pkg, dstDir = dstDir) - mPackagesBackupUtil.backupPermissions(p = p) - mPackagesBackupUtil.backupSsaid(p = p) - - if (pkg.isSuccess) { - // Save config - p.extraInfo.lastBackupTime = DateUtil.getTimestamp() - val id = restoreEntity?.id ?: 0 - restoreEntity = p.copy( - id = id, - indexInfo = p.indexInfo.copy(opType = OpType.RESTORE, cloud = mTaskEntity.cloud, backupDir = mTaskEntity.backupDir), - extraInfo = p.extraInfo.copy(activated = false) - ) - val configDst = PathUtil.getPackageRestoreConfigDst(dstDir = dstDir) - mRootService.writeJson(data = restoreEntity, dst = configDst) - onConfigSaved(path = configDst, archivesRelativeDir = p.archivesRelativeDir) - mPackageDao.upsert(restoreEntity) - mPackageDao.upsert(p) - pkg.update(packageEntity = p) - mTaskEntity.update(successCount = mTaskEntity.successCount + 1) + if (pkg.isSuccess) { + // Save config + p.extraInfo.lastBackupTime = DateUtil.getTimestamp() + val id = restoreEntity?.id ?: 0 + restoreEntity = p.copy( + id = id, + indexInfo = p.indexInfo.copy(opType = OpType.RESTORE, cloud = mTaskEntity.cloud, backupDir = mTaskEntity.backupDir), + extraInfo = p.extraInfo.copy(activated = false) + ) + val configDst = PathUtil.getPackageRestoreConfigDst(dstDir = dstDir) + mRootService.writeJson(data = restoreEntity, dst = configDst) + onConfigSaved(path = configDst, archivesRelativeDir = p.archivesRelativeDir) + mPackageDao.upsert(restoreEntity) + mPackageDao.upsert(p) + pkg.update(packageEntity = p) + mTaskEntity.update(successCount = mTaskEntity.successCount + 1) + } else { + mTaskEntity.update(failureCount = mTaskEntity.failureCount + 1) + } } else { - mTaskEntity.update(failureCount = mTaskEntity.failureCount + 1) + pkg.update(dataType = DataType.PACKAGE_APK, state = OperationState.ERROR) + pkg.update(dataType = DataType.PACKAGE_USER, state = OperationState.ERROR) + pkg.update(dataType = DataType.PACKAGE_USER_DE, state = OperationState.ERROR) + pkg.update(dataType = DataType.PACKAGE_DATA, state = OperationState.ERROR) + pkg.update(dataType = DataType.PACKAGE_OBB, state = OperationState.ERROR) + pkg.update(dataType = DataType.PACKAGE_MEDIA, state = OperationState.ERROR) } - } else { - pkg.update(dataType = DataType.PACKAGE_APK, state = OperationState.ERROR) - pkg.update(dataType = DataType.PACKAGE_USER, state = OperationState.ERROR) - pkg.update(dataType = DataType.PACKAGE_USER_DE, state = OperationState.ERROR) - pkg.update(dataType = DataType.PACKAGE_DATA, state = OperationState.ERROR) - pkg.update(dataType = DataType.PACKAGE_OBB, state = OperationState.ERROR) - pkg.update(dataType = DataType.PACKAGE_MEDIA, state = OperationState.ERROR) + pkg.update(state = if (pkg.isSuccess) OperationState.DONE else OperationState.ERROR) + } finally { + releaseApp(killAppOption, pkg) } - pkg.update(state = if (pkg.isSuccess) OperationState.DONE else OperationState.ERROR) } mTaskEntity.update(processingIndex = mTaskEntity.processingIndex + 1) } diff --git a/source/core/service/src/main/kotlin/com/xayah/core/service/packages/restore/AbstractRestoreService.kt b/source/core/service/src/main/kotlin/com/xayah/core/service/packages/restore/AbstractRestoreService.kt index b1e95fc16b..df75f6426f 100644 --- a/source/core/service/src/main/kotlin/com/xayah/core/service/packages/restore/AbstractRestoreService.kt +++ b/source/core/service/src/main/kotlin/com/xayah/core/service/packages/restore/AbstractRestoreService.kt @@ -112,6 +112,9 @@ internal abstract class AbstractRestoreService : AbstractPackagesService() { val killAppOption = mContext.readKillAppOption().first() log { "Kill app option: $killAppOption" } + // Lift the suspensions that a previous, interrupted task could not lift by itself. + releaseApps() + mPkgEntities.forEachIndexed { index, pkg -> executeAtLeast { NotificationUtil.notify( @@ -125,31 +128,37 @@ internal abstract class AbstractRestoreService : AbstractPackagesService() { log { "Current package: ${pkg.packageEntity}" } killApp(killAppOption, pkg) + try { + pkg.update(state = OperationState.PROCESSING) + val p = pkg.packageEntity + val srcDir = "${mAppsDir}/${p.archivesRelativeDir}" + val userId = if (restoreUser == -1) p.userId else restoreUser + restore(type = DataType.PACKAGE_APK, userId = userId, p = p, t = pkg, srcDir = srcDir) + restore(type = DataType.PACKAGE_USER, userId = userId, p = p, t = pkg, srcDir = srcDir) + restore(type = DataType.PACKAGE_USER_DE, userId = userId, p = p, t = pkg, srcDir = srcDir) + // Re-apply the pause: a restore that just installed the package has started it, and the + // data must not be written while the app is running. + reinforcePause(killAppOption, pkg) + restore(type = DataType.PACKAGE_DATA, userId = userId, p = p, t = pkg, srcDir = srcDir) + restore(type = DataType.PACKAGE_OBB, userId = userId, p = p, t = pkg, srcDir = srcDir) + restore(type = DataType.PACKAGE_MEDIA, userId = userId, p = p, t = pkg, srcDir = srcDir) + if (mContext.readRestorePermissions().first()) { + mPackagesRestoreUtil.restorePermissions(userId = userId, p = p) + } + if (mContext.readRestoreSsaid().first()) { + mPackagesRestoreUtil.restoreSsaid(userId = userId, p = p) + } - pkg.update(state = OperationState.PROCESSING) - val p = pkg.packageEntity - val srcDir = "${mAppsDir}/${p.archivesRelativeDir}" - val userId = if (restoreUser == -1) p.userId else restoreUser - restore(type = DataType.PACKAGE_APK, userId = userId, p = p, t = pkg, srcDir = srcDir) - restore(type = DataType.PACKAGE_USER, userId = userId, p = p, t = pkg, srcDir = srcDir) - restore(type = DataType.PACKAGE_USER_DE, userId = userId, p = p, t = pkg, srcDir = srcDir) - restore(type = DataType.PACKAGE_DATA, userId = userId, p = p, t = pkg, srcDir = srcDir) - restore(type = DataType.PACKAGE_OBB, userId = userId, p = p, t = pkg, srcDir = srcDir) - restore(type = DataType.PACKAGE_MEDIA, userId = userId, p = p, t = pkg, srcDir = srcDir) - if (mContext.readRestorePermissions().first()) { - mPackagesRestoreUtil.restorePermissions(userId = userId, p = p) - } - if (mContext.readRestoreSsaid().first()) { - mPackagesRestoreUtil.restoreSsaid(userId = userId, p = p) - } - - if (pkg.isSuccess) { - pkg.update(packageEntity = p) - mTaskEntity.update(successCount = mTaskEntity.successCount + 1) - } else { - mTaskEntity.update(failureCount = mTaskEntity.failureCount + 1) + if (pkg.isSuccess) { + pkg.update(packageEntity = p) + mTaskEntity.update(successCount = mTaskEntity.successCount + 1) + } else { + mTaskEntity.update(failureCount = mTaskEntity.failureCount + 1) + } + pkg.update(state = if (pkg.isSuccess) OperationState.DONE else OperationState.ERROR) + } finally { + releaseApp(killAppOption, pkg) } - pkg.update(state = if (pkg.isSuccess) OperationState.DONE else OperationState.ERROR) } mTaskEntity.update(processingIndex = mTaskEntity.processingIndex + 1) } diff --git a/source/core/service/src/main/kotlin/com/xayah/core/service/util/PackagesBackupUtil.kt b/source/core/service/src/main/kotlin/com/xayah/core/service/util/PackagesBackupUtil.kt index 1434d1b02a..1151c2007c 100644 --- a/source/core/service/src/main/kotlin/com/xayah/core/service/util/PackagesBackupUtil.kt +++ b/source/core/service/src/main/kotlin/com/xayah/core/service/util/PackagesBackupUtil.kt @@ -188,6 +188,16 @@ class PackagesBackupUtil @Inject constructor( private val tarCt = CompressionType.TAR fun getIconsDst(dstDir: String) = "${dstDir}/$IconRelativeDir.${tarCt.suffix}" + + /** + * `tar` exits with 1 when some files differ, meaning a file changed or disappeared while it was + * being read. That is exactly what happens when the data of an app that is still running is + * archived, and the archive itself is perfectly readable, so "some files differ" must not fail + * the package on its own: [CommonBackupUtil.testArchive] is the real verdict on the archive. + * Exit code 2 (fatal) and a missing/timed out result still fail. + */ + private fun ShellResult.isAcceptableTarResult() = code == 0 || code == 1 + suspend fun backupIcons(dstDir: String): ShellResult = run { log { "Backing up icons..." } @@ -244,7 +254,7 @@ class PackagesBackupUtil @Inject constructor( } else { Tar.compressInCur(cur = srcDir, src = "./*.apk", dst = dst, extra = ct.getCompressPara(context.readCompressionLevel().first())) .also { result -> - isSuccess = result.isSuccess + isSuccess = result.isAcceptableTarResult() out.addAll(result.out) } commonBackupUtil.testArchive(src = dst, ct = ct).also { result -> @@ -338,7 +348,7 @@ class PackagesBackupUtil @Inject constructor( dst = dst, extra = ct.getCompressPara(context.readCompressionLevel().first()) ).also { result -> - isSuccess = result.isSuccess + isSuccess = result.isAcceptableTarResult() out.addAll(result.out) } commonBackupUtil.testArchive(src = dst, ct = ct).also { result -> diff --git a/source/core/util/src/main/kotlin/com/xayah/core/util/SuspendUtil.kt b/source/core/util/src/main/kotlin/com/xayah/core/util/SuspendUtil.kt new file mode 100644 index 0000000000..17914358db --- /dev/null +++ b/source/core/util/src/main/kotlin/com/xayah/core/util/SuspendUtil.kt @@ -0,0 +1,93 @@ +package com.xayah.core.util + +import android.content.Context +import com.xayah.core.util.command.BaseUtil +import java.io.File +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.NonCancellable +import kotlinx.coroutines.withContext + +/** + * Tracks the packages that were paused (force-stopped and suspended) by the running task. + * + * A suspended package stays unusable until it is unsuspended, so the list is persisted to the app's + * private storage: a task that is killed before it can resume its packages leaves a record behind and + * [resumeAll] lifts every leftover suspension the next time a task starts. + * + * Every entry point is non-cancellable and never throws: pausing an app is a best-effort helper of the + * task, a failure in here must not change the outcome of the backup or of the restore it belongs to. + */ +object SuspendUtil { + private const val PendingFileName = "suspended_packages.txt" + + private fun pendingFile(context: Context): File = File(context.filesDir(), PendingFileName) + + private fun entryOf(userId: Int, packageName: String): String = "$userId:$packageName" + + private fun readEntries(context: Context): List = runCatching { + pendingFile(context).takeIf { it.isFile }?.readLines().orEmpty() + }.getOrDefault(emptyList()).map { it.trim() }.filter { it.isNotEmpty() } + + private fun writeEntries(context: Context, entries: List) { + runCatching { + val file = pendingFile(context) + if (entries.isEmpty()) { + file.delete() + } else { + file.writeText(entries.distinct().joinToString(separator = "\n")) + } + } + } + + private fun parseEntry(entry: String): Pair? { + val separator = entry.indexOf(':') + if (separator <= 0 || separator == entry.lastIndex) { + return null + } + return entry.substring(0, separator).toIntOrNull()?.let { userId -> userId to entry.substring(separator + 1) } + } + + private suspend fun nonCancellable(default: T, block: suspend () -> T): T = + withContext(Dispatchers.IO + NonCancellable) { + runCatching { block() }.getOrElse { default } + } + + /** + * Force-stops and suspends [packageName], and remembers it until [resumePackage] or [resumeAll] runs. + * + * Safe to call repeatedly: an already suspended package is force-stopped and suspended again, which is + * exactly what is needed when the user (or the system) managed to start it in the meantime. + * + * @return false when the package was skipped or the suspension failed. + */ + suspend fun suspendPackage(context: Context, userId: Int, packageName: String): Boolean = nonCancellable(false) { + if (packageName == context.packageName || packageName == "android") { + // Suspending the running task or the framework itself could not be undone in time. + false + } else { + // Recorded before suspending: an interruption in between only causes a harmless unsuspend. + writeEntries(context, readEntries(context) + entryOf(userId, packageName)) + BaseUtil.suspendPackage(context = context, userId = userId, packageName = packageName) + } + } + + /** + * Lifts the suspension of [packageName] and drops its record. + */ + suspend fun resumePackage(context: Context, userId: Int, packageName: String) = nonCancellable(Unit) { + val entry = entryOf(userId, packageName) + // Always unsuspend: the record may be missing after an update while the package is still paused. + BaseUtil.unsuspendPackage(context = context, userId = userId, packageName = packageName) + writeEntries(context, readEntries(context).filter { it != entry }) + } + + /** + * Lifts every suspension recorded by a previous task. + */ + suspend fun resumeAll(context: Context) = nonCancellable(Unit) { + readEntries(context).mapNotNull { parseEntry(it) }.forEach { (userId, packageName) -> + BaseUtil.unsuspendPackage(context = context, userId = userId, packageName = packageName) + } + writeEntries(context, emptyList()) + } +} diff --git a/source/core/util/src/main/kotlin/com/xayah/core/util/command/BaseUtil.kt b/source/core/util/src/main/kotlin/com/xayah/core/util/command/BaseUtil.kt index 504a8af071..9da9915991 100644 --- a/source/core/util/src/main/kotlin/com/xayah/core/util/command/BaseUtil.kt +++ b/source/core/util/src/main/kotlin/com/xayah/core/util/command/BaseUtil.kt @@ -156,6 +156,48 @@ object BaseUtil { } } + /** + * Force-stops [packageName] and suspends it afterwards. + * + * Suspension keeps the package from being started again by the launcher, broadcasts, + * services, jobs or alarms for as long as it lasts, and the launcher shows its icon greyed out. + * It has to be lifted by [unsuspendPackage]; otherwise the package stays unusable. + * `pm suspend` requires `android.permission.SUSPEND_APPS`, which only root/shell holds. + */ + suspend fun suspendPackage(context: Context, userId: Int, packageName: String): Boolean = runCatching { + val shell = getNewShell(context) + if (shell != null) { + val cmd = """ + am force-stop --user "$userId" "$packageName" &>/dev/null + pm suspend --user "$userId" "$packageName" &>/dev/null + """.trimIndent() + execute(cmd, shell = shell, timeout = 5).code == 0 + } else { + log { "suspendPackage" to "Failed to get a new shell!" } + false + } + }.getOrElse { + // Pausing must never abort the task that asked for it. + log { "suspendPackage" to "Failed: $it" } + false + } + + suspend fun unsuspendPackage(context: Context, userId: Int, packageName: String): Boolean = runCatching { + val shell = getNewShell(context) + if (shell != null) { + val cmd = """ + pm unsuspend --user "$userId" "$packageName" &>/dev/null + """.trimIndent() + execute(cmd, shell = shell, timeout = 5).code == 0 + } else { + log { "unsuspendPackage" to "Failed to get a new shell!" } + false + } + }.getOrElse { + log { "unsuspendPackage" to "Failed: $it" } + false + } + suspend fun mkdirs(dst: String) = withIOContext { runCatching { val file = File(dst) diff --git a/source/feature/main/settings/src/main/kotlin/com/xayah/feature/main/settings/backup/Index.kt b/source/feature/main/settings/src/main/kotlin/com/xayah/feature/main/settings/backup/Index.kt index 44eeb6ba25..4a412e6432 100644 --- a/source/feature/main/settings/src/main/kotlin/com/xayah/feature/main/settings/backup/Index.kt +++ b/source/feature/main/settings/src/main/kotlin/com/xayah/feature/main/settings/backup/Index.kt @@ -83,9 +83,16 @@ fun PageBackupSettings() { } val items = stringArrayResource(id = R.array.kill_app_options) - val dialogItems by remember(items) { + // Describe how every option is implemented, so the names alone are not the only hint. + val descs = listOf( + R.string.kill_app_option_disabled_desc, + R.string.kill_app_option_i_desc, + R.string.kill_app_option_ii_desc, + R.string.kill_app_option_iii_desc, + ).map { stringResource(id = it) } + val dialogItems by remember(items, descs) { mutableStateOf(items.mapIndexed { index, s -> - DialogRadioItem(enum = KillAppOption.indexOf(index), title = s, desc = null) + DialogRadioItem(enum = KillAppOption.indexOf(index), title = s, desc = descs.getOrNull(index)) }) } val currentOption by context.readKillAppOption().collectAsStateWithLifecycle(initialValue = KillAppOption.OPTION_II) @@ -93,6 +100,7 @@ fun PageBackupSettings() { Selectable( title = stringResource(id = R.string.kill_app_options), value = stringResource(id = R.string.kill_app_options_desc), + desc = descs.getOrNull(currentIndex), current = items[currentIndex] ) { val (state, selectedIndex) = dialogState.select( diff --git a/source/feature/main/settings/src/main/kotlin/com/xayah/feature/main/settings/restore/Index.kt b/source/feature/main/settings/src/main/kotlin/com/xayah/feature/main/settings/restore/Index.kt index 1ad9ab495e..3eb869d3dc 100644 --- a/source/feature/main/settings/src/main/kotlin/com/xayah/feature/main/settings/restore/Index.kt +++ b/source/feature/main/settings/src/main/kotlin/com/xayah/feature/main/settings/restore/Index.kt @@ -59,9 +59,16 @@ fun PageRestoreSettings() { ) { Column { val items = stringArrayResource(id = R.array.kill_app_options) - val dialogItems by remember(items) { + // Describe how every option is implemented, so the names alone are not the only hint. + val descs = listOf( + R.string.kill_app_option_disabled_desc, + R.string.kill_app_option_i_desc, + R.string.kill_app_option_ii_desc, + R.string.kill_app_option_iii_desc, + ).map { stringResource(id = it) } + val dialogItems by remember(items, descs) { mutableStateOf(items.mapIndexed { index, s -> - DialogRadioItem(enum = KillAppOption.indexOf(index), title = s, desc = null) + DialogRadioItem(enum = KillAppOption.indexOf(index), title = s, desc = descs.getOrNull(index)) }) } val currentOption by context.readKillAppOption().collectAsStateWithLifecycle(initialValue = KillAppOption.OPTION_II) @@ -69,6 +76,7 @@ fun PageRestoreSettings() { Selectable( title = stringResource(id = R.string.kill_app_options), value = stringResource(id = R.string.kill_app_options_desc), + desc = descs.getOrNull(currentIndex), current = items[currentIndex] ) { val (state, selectedIndex) = dialogState.select( diff --git a/source/feature/main/settings/src/main/res/values/ids.xml b/source/feature/main/settings/src/main/res/values/ids.xml index 6ad4d57421..30be41e1f8 100644 --- a/source/feature/main/settings/src/main/res/values/ids.xml +++ b/source/feature/main/settings/src/main/res/values/ids.xml @@ -60,6 +60,10 @@ + + + +