diff --git a/README.en.md b/README.en.md
index d7df44e..c8eb6f1 100644
--- a/README.en.md
+++ b/README.en.md
@@ -63,7 +63,7 @@ modavd [--root
] [--json] [--quiet] [--verbose] [args]
| `list` | All instances and their status |
| `info ` / `status ` | Details of one instance / its status |
| `create [--index N] [--title T] [--memory 6G] [--cpu N] [--data-gb auto\|N] [--fps 1-60] [--resolution 1080\|720] [--dpi auto\|N] [--orientation landscape\|portrait] [--no-bridge] [--timeout 1200]`, `create --resume N` | Create an instance (automatic data disk by default, see below), then start it once in the background, headless, to finish initialization, and shut it down (see below). The arm64 execution bridge is included by default; `--no-bridge` records that this instance does not want the bridge, so it is not installed on later starts either. New instances never get the Google Play Store; add it afterwards with `playstore install`. `--resume N` redoes the initialization of an instance whose creation failed |
-| `set [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080\|720] [--dpi auto\|N] [--orientation landscape\|portrait] [--data-gb auto\|N] [--diagnostics on\|off] [--sound on\|off] [--boss-key combination\|none]` | Change settings. Diagnostics and the boss key apply immediately; other settings take effect at the next start. `--data-gb auto` makes the data disk automatic, `--data-gb N` gives it a fixed size (see below); the size can only be increased, and game data is untouched: the emulator (from 0.36) grows the disk image at start and grows the file system online after boot. A disk created before 0.36 at 16 GB or smaller can only be grown to just below the next backup group (a 16 GB disk to about 30 GB). `--sound on` gives this instance sound from its next start (windowed and headless, at some extra CPU); the default `off` boots without a sound card; stored as `instances..sound` in `mas-avd.json`. `--boss-key` is this instance's boss key (see the ModAVD.exe manager section), for example `Ctrl+Alt+Shift+1`; `none` means no boss key; Windows only. |
+| `set [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080\|720] [--dpi auto\|N] [--orientation landscape\|portrait] [--data-gb auto\|N] [--diagnostics on\|off] [--sound on\|off] [--app-keepalive on\|off] [--boss-key combination\|none]` | Change settings. Diagnostics and the boss key apply immediately; other settings take effect at the next start. `--data-gb auto` makes the data disk automatic, `--data-gb N` gives it a fixed size (see below); the size can only be increased, and game data is untouched: the emulator (from 0.36) grows the disk image at start and grows the file system online after boot. A disk created before 0.36 at 16 GB or smaller can only be grown to just below the next backup group (a 16 GB disk to about 30 GB). `--sound on` gives this instance sound from its next start (windowed and headless, at some extra CPU); the default `off` boots without a sound card; stored as `instances..sound` in `mas-avd.json`. `--boss-key` is this instance's boss key (see the ModAVD.exe manager section), for example `Ctrl+Alt+Shift+1`; `none` means no boss key; Windows only. |
| `proxy [on\|off\|test] [--server URL\|auto] [--add PKG] [--remove PKG] [--apps PKG]` | Per-app proxy: the listed apps go through a proxy, the others direct (see below) |
| `delete --yes` | Delete a stopped instance, together with its game data |
| `clone [--title T]` | Copy a stopped instance whole into a new one (games, logins and settings included): the new one takes the smallest free index and its ports, everything else follows the source. The data disk is copied whole, so the two do not affect each other; without enough free space the command fails (`precheck_failed`) and copies nothing, and a failed or canceled copy is deleted. Both have the same Android device IDs (Android ID, GSF ID) |
@@ -81,6 +81,8 @@ modavd [--root ] [--json] [--quiet] [--verbose] [args]
| `update [status\|check\|prepare\|install\|recover] [--source github\|mirrorchyan] [--cdk-dpapi BASE64] [--automas-version V]` | Update the whole ModAVD package in the root folder, using the update source from "Settings", or the source and CDK the caller passes for this run (see "Updating ModAVD") |
| `servers`, `version`, `mcp`, `help [command]` | |
+The instance setting **Keep background apps** takes effect at the next boot. With the default `--app-keepalive off`, ModAVD force-stops a third-party app after 60 continuous seconds away from the foreground. Returning to the app cancels its timer. Home apps, the active keyboard, system apps and Google services are exempt. Set `--app-keepalive on` to leave background apps running. The setting is stored as `instances..appKeepalive` in `mas-avd.json`. Older instances without the key use `off`. The MCP tool `update_instance` takes the boolean `app_keepalive`.
+
Apple Silicon macOS supports `report-config` and `collect-info`, including hardware, macOS, HVF, Metal and component versions. Game lists are queried only through an existing private ADB server and running instances with verified ownership; no service is started. The package contains an allowlist of local instance settings and at most eight emulator logs, capped at 2 MiB each and 20 MiB of text in total. Common credential fields, paths and device identifiers are filtered. macOS does not collect screenshots, system dumps or other applications' logs. Review the package before sharing it. Clipboard copying and Finder reveal can be disabled with `--no-clipboard` and `--no-explorer`.
- Write `` as `3` or `mas_3` (0-9, except 5). Memory is written as `6144`, `6144M` or `6G`, with only five tiers: 3 / 4 / 5 / 6 / 8 GB. Cores are 2 / 4 / 6, and the frame rate is any whole number from 1 to 60 (default 60).
@@ -401,6 +403,8 @@ Tests run on Windows only. Optional environment variables:
The native regional check is `python scripts/test_regional_guest.py --root --legacy-cli --lock `. Copy an independent SDK into the test root and explicitly set `portBase: 34100`, `adbServerPort: 34198`, `scriptAdbServerPort: 34199`, and `shareDefaultAdbServer: false`. The runner validates these conditions. The test holds an exclusive handle through normal shutdown and cleanup. English-host inputs and host time-zone changes are injected; they do not replace acceptance on two real Windows display-language environments.
+To check background app timers, push `scripts/test_app_keepalive_guest.sh` to an Android 14 test instance. In its shell, run `sh test_app_keepalive_guest.sh /data/local/tmp/modavd-app-keepalive.sh` from the directory containing the test script. The check takes about 70 seconds and simulates app switches and a failed foreground query to verify retry and cancellation.
+
The 4 KiB guest helper in `internal/guest/regional/Regional.java` includes its compiled DEX. Normal builds need neither Java nor an Android SDK. After changing the helper, rebuild and compare its bytes using a local JDK and the pinned D8: `python internal/guest/regional/generate.py --r8 --check`. The script records the download URL and SHA-256. Regenerate the CLDR table with `python internal/regional/generate.py ` using the pinned input.
## Standalone download and hashes
diff --git a/README.md b/README.md
index 62e94dc..a0d0411 100644
--- a/README.md
+++ b/README.md
@@ -63,7 +63,7 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数]
| `list` | 全部实例和状态 |
| `info ` / `status ` | 一台实例的详细信息 / 状态 |
| `create [--index N] [--title T] [--memory 6G] [--cpu N] [--data-gb auto\|N] [--fps 1-60] [--resolution 1080\|720] [--dpi auto\|N] [--orientation landscape\|portrait] [--no-bridge] [--timeout 1200]`、`create --resume N` | 新建(数据盘默认自动扩盘,见下),并在后台无头开机一次把初始化做完再关机(见下)。默认带 arm64 执行桥;`--no-bridge` 记下这台不要桥,以后开机也不装。新建的实例不带 Google Play 商店,要的话建好后用 `playstore install`。`--resume N` 重做新建失败的那台的初始化 |
-| `set [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080\|720] [--dpi auto\|N] [--orientation landscape\|portrait] [--data-gb auto\|N] [--diagnostics on\|off] [--sound on\|off] [--boss-key 组合\|none]` | 修改;诊断模式和老板键立即生效,其余设置下次开机生效。`--data-gb auto` 改成自动扩盘,`--data-gb N` 改成指定大小(见下);大小只能改大,游戏数据不动:模拟器(0.36 起)开机时扩磁盘镜像,开机后在线扩文件系统。0.36 之前按 16 GB 及以下建的盘只能扩到下一个备份组之前(16 GB 约到 30 GB)。`--sound on` 让这台下次开机起有声音(带窗口和无头都是,会多占一些 CPU),默认 `off` 不带声卡;记在 `mas-avd.json` 的 `instances..sound`。`--boss-key` 是这台的老板键(见「管理器 ModAVD.exe」一节),比如 `Ctrl+Alt+Shift+1`,`none` 是不要,只有 Windows。 |
+| `set [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080\|720] [--dpi auto\|N] [--orientation landscape\|portrait] [--data-gb auto\|N] [--diagnostics on\|off] [--sound on\|off] [--app-keepalive on\|off] [--boss-key 组合\|none]` | 修改;诊断模式和老板键立即生效,其余设置下次开机生效。`--data-gb auto` 改成自动扩盘,`--data-gb N` 改成指定大小(见下);大小只能改大,游戏数据不动:模拟器(0.36 起)开机时扩磁盘镜像,开机后在线扩文件系统。0.36 之前按 16 GB 及以下建的盘只能扩到下一个备份组之前(16 GB 约到 30 GB)。`--sound on` 让这台下次开机起有声音(带窗口和无头都是,会多占一些 CPU),默认 `off` 不带声卡;记在 `mas-avd.json` 的 `instances..sound`。`--boss-key` 是这台的老板键(见「管理器 ModAVD.exe」一节),比如 `Ctrl+Alt+Shift+1`,`none` 是不要,只有 Windows。 |
| `proxy [on\|off\|test] [--server URL\|auto] [--add 包名] [--remove 包名] [--apps 包名]` | 按应用走代理:名单里的应用走代理,其余直连(见下) |
| `delete --yes` | 删除已关机的实例,连同游戏数据 |
| `clone [--title T]` | 把已关机的实例整份复制成一台新实例(游戏、登录状态、设置都带上):新实例用最小的空闲编号和它的端口,其余设置照源实例;数据盘整份复制,两台互不影响,可用空间不够时报错(`precheck_failed`)、什么都不复制;失败或取消时复制到一半的会删掉。两台的安卓设备标识(Android ID、GSF ID)相同 |
@@ -83,6 +83,8 @@ modavd [--root <目录>] [--json] [--quiet] [--verbose] <命令> [参数]
| `update [status\|check\|prepare\|install\|recover] [--source github\|mirrorchyan] [--cdk-dpapi BASE64] [--automas-version V]` | 更新根目录里的整个 ModAVD 包,按「设置」里的更新源,或调用方这次传的更新源和 CDK(见「更新 ModAVD」) |
| `servers`、`version`、`mcp`、`help [命令]` | |
+实例设置里的「应用保活」下次开机生效。默认 `--app-keepalive off`,第三方应用连续离开前台满 60 秒后由 ModAVD 结束,中途切回就取消计时。桌面、当前输入法、系统包和谷歌服务豁免。`--app-keepalive on` 保留后台应用。设置记在 `mas-avd.json` 的 `instances..appKeepalive`,旧实例没有这个字段时按关闭处理。MCP 的 `update_instance` 接受布尔参数 `app_keepalive`。
+
Apple Silicon macOS 支持 `report-config` 和 `collect-info`:读取硬件、macOS、HVF、Metal 和组件版本;游戏列表只向归属已确认的运行实例与现有私有 ADB 查询,不启动服务。问题包只收本目录的实例配置白名单和最多 8 份模拟器日志,每份最多 2 MiB、总文本最多 20 MiB,过滤常见凭据字段、路径和设备标识。macOS 不收截图、系统转储或其他应用日志;分享前请检查问题包。默认复制配置到剪贴板、用 Finder 显示问题包,自动化可用 `--no-clipboard` / `--no-explorer`。
- `` 写成 `3` 或 `mas_3`(0–9,5 除外);内存写成 `6144`、`6144M` 或 `6G`,只有 3 / 4 / 5 / 6 / 8 GB 五档,核数 2 / 4 / 6,帧率 1–60 的整数(默认 60)。
@@ -404,6 +406,8 @@ go test ./...
语言/时区的真实客体验收用 `python scripts/test_regional_guest.py --root <本工作树/out/全新测试根> --legacy-cli <旧版命令行> --lock <共享验收锁文件>`。测试根须复制独立 SDK,并明确设置 `portBase: 34100`、`adbServerPort: 34198`、`scriptAdbServerPort: 34199`、`shareDefaultAdbServer: false`。脚本验证这些条件;测试持有独占句柄直到正常关机和清理完成。英文宿主及宿主时区变化采用注入输入,不代替两种真实 Windows 的验收。
+在 Android 14 测试实例的 shell 里运行 `sh test_app_keepalive_guest.sh /data/local/tmp/modavd-app-keepalive.sh` 可复测后台应用计时。先将 `scripts/test_app_keepalive_guest.sh` 推到测试实例。脚本用模拟的应用切换和前台查询失败事件验证超时重试、切回取消,约需 70 秒。
+
`internal/guest/regional/Regional.java` 的 4 KiB 客体助手随源码附带 DEX。普通构建不用 Java 或 Android SDK;修改助手后,用本地 JDK 和指定 D8 重建,并核对字节:`python internal/guest/regional/generate.py --r8 --check`。脚本记录下载地址和 SHA-256。CLDR 表用 `python internal/regional/generate.py ` 从固定版本重建。
## 单独下载与哈希
diff --git a/internal/cli/commands.go b/internal/cli/commands.go
index fd9c251..641f944 100644
--- a/internal/cli/commands.go
+++ b/internal/cli/commands.go
@@ -96,6 +96,7 @@ var (
optLanguage = flagSpec{"language", kindString, "host|preserve|语言", "Windows:host 按宿主界面语言设置一次,preserve 保持安卓语言,或指定 zh-CN、en-US 等语言"}
optTimeZone = flagSpec{"timezone", kindString, "host|preserve|IANA", "Windows:host 每次冷启动跟随宿主,preserve 沿用原行为,或指定 Asia/Shanghai、Etc/UTC 等 IANA 时区"}
optDiagnostics = flagSpec{"diagnostics", kindString, "on|off", "诊断模式:即时增加日志保留;off 立即删回平常规则"}
+ optAppKeepalive = flagSpec{"app-keepalive", kindString, "on|off", "应用保活:默认 off,第三方应用连续在后台满 60 秒后结束;on 保留后台应用。下次开机生效。"}
optSound = flagSpec{"sound", kindString, "on|off", "声音:on 下次开机起带声卡、电脑出声(会多占一些 CPU),off 照旧不带(默认)"}
optBossKey = flagSpec{"boss-key", kindString, "组合", "老板键,比如 Ctrl+Alt+Shift+1(Ctrl、Alt、Shift 至少带一个,不收 Win);none 是不要(只有 Windows)"}
optYes = flagSpec{"yes", kindBool, "", "确认删除(连同游戏数据)"}
@@ -218,14 +219,14 @@ func init() {
run: runCreate, human: humanCreate, exit: exitBatch,
},
{
- name: "set", args: " [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--data-gb auto|N] [--language host|preserve|语言] [--timezone host|preserve|IANA] [--diagnostics on|off] [--sound on|off] [--boss-key 组合|none]",
+ name: "set", args: " [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--data-gb auto|N] [--language host|preserve|语言] [--timezone host|preserve|IANA] [--diagnostics on|off] [--sound on|off] [--app-keepalive on|off] [--boss-key 组合|none]",
summary: "修改实例设置、诊断模式和老板键",
details: "至少给一个选项。诊断模式和老板键立即生效;其它改动下次开机生效。诊断模式最多多用约 4 GiB 磁盘和 48 MiB 客体内存,日志可能含账号信息,只存本机;关闭立即删回平常保留规则。" +
dataDiskHelp + "数据盘只能改大,游戏数据不动:下次开机时模拟器(0.36 起)扩大磁盘镜像,开机后再在线扩大文件系统。" +
"--sound on 让这台下次开机起有声音(带窗口和无头都是),会多占一些 CPU;默认 off。" +
"--boss-key 是这台的老板键:管理器开着时(窗口关了、留在托盘也算),按一下藏起这台带窗口运行的模拟器窗口,再按一下叫回来;" +
"几台设成同一个键就一起藏、一起显示。没设过时编号 0–9 默认 Ctrl+Alt+Shift+编号,超过 9 没有;none 是不要。立即生效,只有 Windows。",
- flags: []flagSpec{optTitle, optMemory, optCPU, optFPS, optResolution, optDPI, optOrientation, optDataGB, optLanguage, optTimeZone, optDiagnostics, optSound, optBossKey},
+ flags: []flagSpec{optTitle, optMemory, optCPU, optFPS, optResolution, optDPI, optOrientation, optDataGB, optLanguage, optTimeZone, optDiagnostics, optSound, optAppKeepalive, optBossKey},
posNames: []string{"实例编号"}, minPos: 1, maxPos: 1,
final: true,
run: runSet, human: humanOf(formatUpdate),
@@ -695,13 +696,21 @@ func buildUpdateRequest(inv *invocation) (emu.UpdateRequest, error) {
on := value == "on"
req.Sound = &on
}
+ if inv.isSet("app-keepalive") {
+ value := strings.ToLower(inv.strOpt("app-keepalive"))
+ if value != "on" && value != "off" {
+ return req, errs.New(errs.InvalidArgument, "--app-keepalive 只能是 on 或 off")
+ }
+ on := value == "on"
+ req.AppKeepalive = &on
+ }
if inv.isSet("boss-key") {
k := inv.strOpt("boss-key")
req.BossKey = &k
}
if req.Title == nil && req.MemoryMB == nil && req.CPU == nil && req.FPS == nil && req.Resolution == nil && req.DPI == nil && req.Orientation == nil && req.DataPartitionGB == nil &&
- !req.DataDiskAuto && req.Diagnostics == nil && req.Sound == nil && req.BossKey == nil && req.Language == nil && req.TimeZone == nil {
- return req, errs.New(errs.Usage, "没有要改的内容:至少给 --title、--memory、--cpu、--fps、--resolution、--dpi、--orientation、--data-gb、--language、--timezone、--diagnostics、--sound、--boss-key 中的一个").
+ !req.DataDiskAuto && req.Diagnostics == nil && req.Sound == nil && req.AppKeepalive == nil && req.BossKey == nil && req.Language == nil && req.TimeZone == nil {
+ return req, errs.New(errs.Usage, "没有要改的内容:至少给 --title、--memory、--cpu、--fps、--resolution、--dpi、--orientation、--data-gb、--language、--timezone、--diagnostics、--sound、--app-keepalive、--boss-key 中的一个").
WithAdvice(findCommand("set").usageAdvice())
}
return req, nil
diff --git a/internal/cli/format.go b/internal/cli/format.go
index 84d93f6..4d72b2c 100644
--- a/internal/cli/format.go
+++ b/internal/cli/format.go
@@ -279,6 +279,7 @@ func formatInfo(w io.Writer, in *emu.InstanceInfo) {
kv("核数", intOrDash(cfg.CPU))
kv("帧率", intOrDash(cfg.FPS))
kv("声音", onOff(cfg.Sound))
+ kv("应用保活", onOff(cfg.AppKeepalive))
kv("数据盘", dataDiskText(cfg)+","+dataSpaceSummary(in.DataSpace))
if in.DataSpace.Message != "" {
kv("数据盘提示", dataSpaceNote(in.DataSpace))
@@ -444,6 +445,9 @@ func appliedParts(applied map[string]any) []string {
} else {
parts = append(parts, "诊断模式 关")
}
+ case "app_keepalive":
+ on, _ := v.(bool)
+ parts = append(parts, "应用保活 "+onOff(on))
case "sound":
on, _ := v.(bool)
parts = append(parts, "声音 "+onOff(on))
diff --git a/internal/emu/afterboot.go b/internal/emu/afterboot.go
index 59c19bf..06f6ce6 100644
--- a/internal/emu/afterboot.go
+++ b/internal/emu/afterboot.go
@@ -231,6 +231,13 @@ func (m *Manager) afterBoot(ctx context.Context, inst *avd.Instance, mode bootSe
m.ensurePixelLauncherRemoved(ctx, i)
}
},
+ func() {
+ // Changing the switch while running takes effect after reboot. Adopting an
+ // already configured boot must keep the current watcher and its timers.
+ if mode != setupAdopted {
+ m.setupAppKeepalive(ctx, i)
+ }
+ },
// 10) orientation: the display stays landscape (persistent; set every boot so old instances get it)
func() { m.setupOrientation(ctx, i) },
// 10b) hand the clusters the guest freed back to the host, at most once a day (best effort, see autotrim.go)
diff --git a/internal/emu/app_keepalive.go b/internal/emu/app_keepalive.go
new file mode 100644
index 0000000..b663ed6
--- /dev/null
+++ b/internal/emu/app_keepalive.go
@@ -0,0 +1,37 @@
+// Copyright 2026 jinghero
+package emu
+
+import (
+ "context"
+ "strconv"
+
+ "modavd/internal/guest"
+ "modavd/internal/jsonord"
+)
+
+const appKeepaliveKey = "appKeepalive"
+
+// Keep background apps if an existing setting cannot be interpreted. An absent
+// setting is the supported legacy configuration and uses the default (off).
+func keepBackgroundApps(meta *jsonord.Obj) bool {
+ field := meta.Get(appKeepaliveKey)
+ on, valid := field.BoolVal()
+ return on || (field != nil && !valid)
+}
+
+func (m *Manager) setupAppKeepalive(ctx context.Context, i int) {
+ meta, err := m.Root.ReadMetadata()
+ if err != nil {
+ m.Log.Warnf("实例 %d 无法读取应用保活设置,跳过后台应用清理: %v", i, err)
+ return
+ }
+ mode := "off"
+ if keepBackgroundApps(meta.Obj().Get("instances").Obj().Get(strconv.Itoa(i)).Obj()) {
+ mode = "on"
+ }
+ if script, ok := m.pushGuestScript(ctx, i, guest.AppKeepalive); ok {
+ if result := m.shell(ctx, i, "sh "+script+" daemon "+mode, 0); result.Code != 0 {
+ m.Log.Warnf("实例 %d 后台应用清理未启动: %s", i, tail(result.Out, 300))
+ }
+ }
+}
diff --git a/internal/emu/crud.go b/internal/emu/crud.go
index 84b7151..158b587 100644
--- a/internal/emu/crud.go
+++ b/internal/emu/crud.go
@@ -17,6 +17,7 @@ import (
"modavd/internal/diagnostics"
"modavd/internal/errs"
"modavd/internal/host"
+ "modavd/internal/jsonord"
"modavd/internal/logx"
"modavd/internal/root"
)
@@ -317,6 +318,12 @@ func (m *Manager) Update(ctx context.Context, i int, req UpdateRequest) (*Update
applied["time_zone"] = *zone
}
}
+ if req.AppKeepalive != nil {
+ if err := m.Root.UpdateInstanceMeta(i, map[string]*jsonord.Value{appKeepaliveKey: jsonord.NewBool(*req.AppKeepalive)}); err != nil {
+ return nil, err
+ }
+ applied["app_keepalive"] = *req.AppKeepalive
+ }
nextBoot := len(applied) > 0
var cleanup *DiagnosticsCleanup
var warnings []string
@@ -348,7 +355,7 @@ func (m *Manager) Update(ctx context.Context, i int, req UpdateRequest) (*Update
if ok {
p = &q
if nextBoot {
- m.Log.Infof("ModAVD 实例 %d 正在运行,硬件改动下次开机生效", i)
+ m.Log.Infof("ModAVD 实例 %d 正在运行,设置改动下次开机生效", i)
}
}
return &UpdateResult{Instance: m.instanceInfo(ctx, in, p, nil), Applied: applied, AppliesNextBoot: p != nil && nextBoot,
diff --git a/internal/emu/crud_test.go b/internal/emu/crud_test.go
index ced75cc..aa50287 100644
--- a/internal/emu/crud_test.go
+++ b/internal/emu/crud_test.go
@@ -28,6 +28,41 @@ func writeTestFile(t *testing.T, path, content string) {
}
}
+// A keepalive-only edit must also work on a legacy instance without rewriting
+// its hardware settings. Missing means off. An unreadable switch preserves apps.
+func TestUpdateAppKeepalive(t *testing.T) {
+ m, _ := opsTestManager(t)
+ i := createFiles(t, m, nil)
+ if m.mustInfo(t, i).Config.AppKeepalive {
+ t.Fatal("missing appKeepalive must default to off")
+ }
+ path := avd.ConfigPath(m.Root, i)
+ before, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, on := range []bool{true, false} {
+ res, err := m.Update(context.Background(), i, UpdateRequest{AppKeepalive: &on})
+ if err != nil {
+ t.Fatal(err)
+ }
+ saved, valid := m.Root.InstanceMeta(i).Get(appKeepaliveKey).BoolVal()
+ if !valid || saved != on || res.Instance.Config.AppKeepalive != on || res.Applied["app_keepalive"] != on {
+ t.Fatalf("keepalive %v: persisted %v/%v, result %+v", on, saved, valid, res)
+ }
+ }
+ after, err := os.ReadFile(path)
+ if err != nil || string(before) != string(after) {
+ t.Fatalf("config.ini changed or unreadable: %v", err)
+ }
+ if err := m.Root.UpdateInstanceMeta(i, map[string]*jsonord.Value{appKeepaliveKey: jsonord.NewString("invalid")}); err != nil {
+ t.Fatal(err)
+ }
+ if !m.mustInfo(t, i).Config.AppKeepalive {
+ t.Fatal("malformed keepalive switch must preserve apps")
+ }
+}
+
// Leftovers of a delete or create that stopped half-way are deleted like AUTO-MAS's delete_instance does (it lets
// NOT_FOUND through to delete_instance_files), and an explicit create on such an index says how to clear it.
func TestDeleteHalfInstances(t *testing.T) {
diff --git a/internal/emu/status.go b/internal/emu/status.go
index 65896ff..033f6c1 100644
--- a/internal/emu/status.go
+++ b/internal/emu/status.go
@@ -227,6 +227,7 @@ func (m *Manager) instanceInfo(ctx context.Context, in *avd.Instance, p *host.Pr
cfg.DataDiskMode = avd.DataDiskAuto
}
cfg.Sound = avd.SoundMeta(meta)
+ cfg.AppKeepalive = keepBackgroundApps(meta)
info.Config = cfg
if meta != nil {
diff --git a/internal/emu/types.go b/internal/emu/types.go
index 1e821a0..e64c42c 100644
--- a/internal/emu/types.go
+++ b/internal/emu/types.go
@@ -51,6 +51,8 @@ type InstanceConfig struct {
Orientation string `json:"orientation"`
// Sound: the next boot has host sound and a guest sound card (mas-avd.json instances..sound; off by default).
Sound bool `json:"sound"`
+ // AppKeepalive leaves third-party apps running in the background from the next boot.
+ AppKeepalive bool `json:"app_keepalive"`
}
type InstanceInfo struct {
@@ -199,7 +201,8 @@ type UpdateRequest struct {
// with DataPartitionGB.
DataDiskAuto bool
// Sound turns the sound card on or off from the next boot (avd.SoundKey; ModAVD/ModAVD#226).
- Sound *bool
+ Sound *bool
+ AppKeepalive *bool
}
type UpdateResult struct {
diff --git a/internal/guest/guest.go b/internal/guest/guest.go
index 66d5943..8ecb6da 100644
--- a/internal/guest/guest.go
+++ b/internal/guest/guest.go
@@ -97,7 +97,8 @@ const (
DownloadDisk = "modavd-dldisk.sh"
// VulkanMode writes the Vulkan display mode for listed games that have not chosen one, before their first start
// (modavd only, ModAVD/ModAVD#222).
- VulkanMode = "modavd-vkmode.sh"
+ VulkanMode = "modavd-vkmode.sh"
+ AppKeepalive = "modavd-app-keepalive.sh"
)
// RemoteDir is where the scripts go in the guest.
diff --git a/internal/guest/guest_test.go b/internal/guest/guest_test.go
index d61b78a..20a16f3 100644
--- a/internal/guest/guest_test.go
+++ b/internal/guest/guest_test.go
@@ -15,7 +15,7 @@ import (
)
func TestScriptsHaveNoCR(t *testing.T) {
- for _, name := range []string{CPUInfoBind, IdlePoll, WifiFastpath, LibFix, PlayStore, DownloadDisk, VulkanMode} {
+ for _, name := range []string{CPUInfoBind, IdlePoll, WifiFastpath, LibFix, PlayStore, DownloadDisk, VulkanMode, AppKeepalive} {
b, err := Script(name)
if err != nil {
t.Fatalf("%s: %v", name, err)
diff --git a/internal/guest/scripts/modavd-app-keepalive.sh b/internal/guest/scripts/modavd-app-keepalive.sh
new file mode 100644
index 0000000..6fa821c
--- /dev/null
+++ b/internal/guest/scripts/modavd-app-keepalive.sh
@@ -0,0 +1,120 @@
+#!/system/bin/sh
+# Copyright 2026 jinghero
+# Android 14, owner user. Only ActivityTaskManager transitions start or cancel timers.
+# The watcher and its timers disappear with the guest. It runs as adb shell.
+set -f
+lock=/data/local/tmp/modavd-app-keepalive.lock
+
+if [ "$1" = daemon ]; then
+ # Pass the locked file description to the worker on stdin. A repeated boot setup
+ # leaves the existing worker and its pending timers alone.
+ exec 9>"$lock" || exit 1
+ flock -n 0 <&9 || exit 0
+ # The host may repeat unfinished boot tuning after the user saves new settings.
+ # A non-persistent property records the first choice until Android reboots.
+ prop=debug.modavd.app_keepalive
+ mode=$(getprop "$prop") || exit 1
+ if [ -z "$mode" ]; then
+ mode=$2
+ case "$mode" in on|off) ;; *) exit 2 ;; esac
+ setprop "$prop" "$mode" || exit 1
+ fi
+ case "$mode" in on) exit 0 ;; off) ;; *) exit 1 ;; esac
+ nohup setsid sh "$0" watch <&9 >/dev/null 2>&1 &
+ worker=$!
+ sleep 0.1
+ kill -0 "$worker" 2>/dev/null
+ exit $?
+fi
+[ "$1" = watch ] || exit 2
+
+now() {
+ read -r uptime rest < /proc/uptime
+ seconds=${uptime%%.*}
+}
+
+eligible() {
+ typeset pkg=$1 user packages homes ime activity resumed component
+ case "$pkg" in
+ android|com.android.vending|com.google.android.gms|com.google.android.gms.*|com.google.android.gsf|com.google.android.gsf.*|com.google.android.partnersetup) return 1 ;;
+ esac
+ # 1 means exempt, 2 means Android could not confirm the state yet.
+ user=$(am get-current-user) || return 2
+ case "$user" in 0) ;; ''|*[!0-9]*) return 2 ;; *) return 1 ;; esac
+ packages=$(pm list packages -3 --user 0 "$pkg") || return 2
+ printf '%s\n' "$packages" | grep -Fxq "package:$pkg" || return 1
+ homes=$(cmd package query-activities --components --user 0 -a android.intent.action.MAIN -c android.intent.category.HOME) || return 2
+ case "$homes" in */*) ;; *) return 2 ;; esac
+ for component in $homes; do [ "${component%%/*}" != "$pkg" ] || return 1; done
+ ime=$(settings --user 0 get secure default_input_method) || return 2
+ case "$ime" in */*) ;; *) return 2 ;; esac
+ [ "${ime%%/*}" != "$pkg" ] || return 1
+ # Re-read foreground state just before stopping. Treat an unrecognised dump as unknown.
+ activity=$(dumpsys activity activities) || return 2
+ resumed=$(printf '%s\n' "$activity" | sed -nE '/topResumedActivity=|Resumed: ActivityRecord|ResumedActivity: ActivityRecord/s/.* u0 ([A-Za-z0-9_.]+)\/.*/\1/p')
+ [ -n "$resumed" ] || return 2
+ for component in $resumed; do [ "$component" != "$pkg" ] || return 1; done
+}
+
+transition() {
+ typeset payload component pkg entry keep=''
+ payload=${1#*\[0,}
+ [ "$payload" != "$1" ] || return
+ case "$1" in
+ I/wm_set_resumed_activity:*) component=${payload%%,*} ;;
+ I/wm_resume_activity:*) component=${payload##*,}; component=${component%]} ;;
+ I/wm_pause_activity:*) payload=${payload#*,}; component=${payload%%,*} ;;
+ *) return ;;
+ esac
+ case "$component" in */*) pkg=${component%%/*} ;; *) return ;; esac
+ case "$pkg" in ''|*[!a-zA-Z0-9_.]*) return ;; esac
+ for entry in $pending; do
+ [ "${entry%@*}" = "$pkg" ] || keep="$keep $entry"
+ done
+ pending=$keep
+ case "$1" in I/wm_pause_activity:*)
+ now
+ # uptime is rounded down here. Adding 61 never shortens the 60-second grace period.
+ pending="$pending $pkg@$((seconds + 61))"
+ esac
+}
+
+# Block in logcat while idle. A timeout wakes us for the earliest deadline. Drain queued
+# transitions first, including any that arrived while querying package and activity state.
+while true; do
+ pending=''
+ logcat -b events --uid=1000 -v tag -T "$(date +%s.%N)" wm_pause_activity:I wm_resume_activity:I wm_set_resumed_activity:I '*:S' /dev/null; do
+ now
+ wait_for=86400
+ due=''
+ for entry in $pending; do
+ left=$((${entry#*@} - seconds))
+ if [ "$left" -le 0 ]; then due=$entry; wait_for=0.05; break; fi
+ [ "$left" -ge "$wait_for" ] || wait_for=$left
+ done
+ if IFS= read -r -t "$wait_for" line <&3; then transition "$line"; continue; fi
+ [ -n "$due" ] || continue
+ pkg=${due%@*}
+ eligible "$pkg"
+ result=$?
+ if [ "$result" = 0 ]; then
+ if IFS= read -r -t 0.05 line <&3; then transition "$line"; continue; fi
+ kill -0 "$logger" 2>/dev/null || break
+ am force-stop --user 0 "$pkg" || result=2
+ fi
+ pending=${pending/" $due"/}
+ if [ "$result" = 2 ]; then
+ now
+ pending="$pending $pkg@$((seconds + 10))"
+ fi
+ done
+ exec 3<&-
+ wait "$logger"
+ # Reconnect with fresh timers: switches during a logd restart are unknown.
+ sleep 1
+done
diff --git a/internal/i18n/locales/en/cli.json b/internal/i18n/locales/en/cli.json
index 9092674..f52c9b5 100644
--- a/internal/i18n/locales/en/cli.json
+++ b/internal/i18n/locales/en/cli.json
@@ -24,6 +24,7 @@
"--%s 要在 1–%.0f 秒之间,收到 %d": "--%s must be between 1 and %.0f seconds, got %d",
"--after-pid 要给进程号,收到 %d": "--after-pid needs a process ID, got %d",
"--after-pid、--reopen、--reopen-arg、--handoff-id 只能和 install 一起用": "--after-pid, --reopen, --reopen-arg and --handoff-id can only be used with install",
+ "--app-keepalive 只能是 on 或 off": "--app-keepalive must be on or off",
"--count 不能和 --index、--resume 一起用:一次建几台时编号按空闲的从小到大取": "--count cannot be used with --index or --resume: when creating several, the numbers are the free ones from the smallest up",
"--count 要给 1–9 的整数,收到 %d": "--count must be a whole number from 1 to 9, got %d",
"--data-gb 只能是 auto 或 %d–%d 的整数(GB),收到「%s」": "--data-gb must be auto or an integer from %d to %d (GB), got \"%s\"",
@@ -42,7 +43,7 @@
"0.3.0 起没有重启:先 modavd stop ,再 modavd start (要窗口加 --window)": "There is no restart since 0.3.0: run modavd stop , then modavd start (add --window for a window)",
" [--] ": " [--] ",
" [--timeout 秒] <命令...>": " [--timeout SECONDS] ",
- " [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--data-gb auto|N] [--language host|preserve|语言] [--timezone host|preserve|IANA] [--diagnostics on|off] [--sound on|off] [--boss-key 组合|none]": " [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--data-gb auto|N] [--language host|preserve|language] [--timezone host|preserve|IANA] [--diagnostics on|off] [--sound on|off] [--boss-key combo|none]",
+ " [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--data-gb auto|N] [--language host|preserve|语言] [--timezone host|preserve|IANA] [--diagnostics on|off] [--sound on|off] [--app-keepalive on|off] [--boss-key 组合|none]": " [--title T] [--memory M] [--cpu N] [--fps F] [--resolution 1080|720] [--dpi auto|N] [--orientation landscape|portrait] [--data-gb auto|N] [--language host|preserve|language] [--timezone host|preserve|IANA] [--diagnostics on|off] [--sound on|off] [--app-keepalive on|off] [--boss-key combo|none]",
" [on|off|test] [--server URL|auto] [--add 包名] [--remove 包名] [--apps 包名]": " [on|off|test] [--server URL|auto] [--add PACKAGE] [--remove PACKAGE] [--apps PACKAGE]",
"APK 路径": "APK path",
"ARM64 商店文件已准备;当前 macOS 版本尚未开放实例内安装与移除": "ARM64 Store files are ready; this macOS version does not yet support installing or removing them in an instance",
@@ -270,6 +271,9 @@
"帧率 %v": "Frame rate %v",
"帧率:1–60 的整数,默认 60": "Frame rate: an integer from 1 to 60, default 60",
"序列号": "Serial number",
+ "应用保活": "Keep background apps",
+ "应用保活 %v": "Keep background apps %v",
+ "应用保活:默认 off,第三方应用连续在后台满 60 秒后结束;on 保留后台应用。下次开机生效。": "Keep background apps: off (default) stops third-party apps after 60 continuous seconds in the background. Use on to keep them. Takes effect at the next boot.",
"建议:%s\n": "Suggestion: %s\n",
"开": "on",
"开机中": "Starting",
@@ -357,7 +361,7 @@
"没找到根目录:%s(之后每次调用工具时再找)": "Root folder not found: %s (it will be looked for again on each tool call)",
"没有": "None",
"没有正在运行的实例": "No running instances",
- "没有要改的内容:至少给 --title、--memory、--cpu、--fps、--resolution、--dpi、--orientation、--data-gb、--language、--timezone、--diagnostics、--sound、--boss-key 中的一个": "Nothing to change: give at least one of --title, --memory, --cpu, --fps, --resolution, --dpi, --orientation, --data-gb, --language, --timezone, --diagnostics, --sound, --boss-key",
+ "没有要改的内容:至少给 --title、--memory、--cpu、--fps、--resolution、--dpi、--orientation、--data-gb、--language、--timezone、--diagnostics、--sound、--app-keepalive、--boss-key 中的一个": "Nothing to change: give at least one of --title, --memory, --cpu, --fps, --resolution, --dpi, --orientation, --data-gb, --language, --timezone, --diagnostics, --sound, --app-keepalive, --boss-key",
"没生效:%v": "Not in effect: %v",
"没装": "Not installed",
"注意:%v": "Note: %v",
diff --git a/internal/i18n/locales/en/emu.json b/internal/i18n/locales/en/emu.json
index fdc9f73..90938f7 100644
--- a/internal/i18n/locales/en/emu.json
+++ b/internal/i18n/locales/en/emu.json
@@ -96,7 +96,7 @@
"ModAVD 实例 %d 正在用软件渲染(%s):没有可用的显卡驱动,游戏会占满 CPU,请更新显卡驱动": "ModAVD instance %d is using software rendering (%s): no usable graphics driver, games will use all of the CPU; update the graphics driver",
"ModAVD 实例 %d 正在装卸执行桥、Google Play 商店或改 GLES 3.2 开关,稍后再试": "ModAVD instance %d is installing or removing the execution bridge or Google Play Store, or changing the GLES 3.2 switch; try again later",
"ModAVD 实例 %d 正在装或卸执行桥,稍后再试": "ModAVD instance %d is installing or removing the execution bridge; try again later",
- "ModAVD 实例 %d 正在运行,硬件改动下次开机生效": "ModAVD instance %d is running; hardware changes take effect at the next start",
+ "ModAVD 实例 %d 正在运行,设置改动下次开机生效": "ModAVD instance %d is running. The settings take effect at the next start.",
"ModAVD 实例 %d 正带窗口运行,运行中不能换成无头": "ModAVD instance %d is running with a window and cannot switch to headless while running",
"ModAVD 实例 %d 正常关机完成(%.1f s)": "ModAVD instance %d shut down normally (%.1f s)",
"ModAVD 实例 %d 正常关机没成(%s),退回 sync + 控制台 kill": "ModAVD instance %d normal shutdown failed (%s), falling back to sync + console kill",
@@ -298,6 +298,7 @@
"实例 %d 原来是关着的,没做成后已经关机": "Instance %d was off before; it has been shut down after the failure",
"实例 %d 发布开机失败现场失败: %v": "Instance %d: failed to publish the start failure snapshot: %v",
"实例 %d 取不到清理锁,仍发布已完成的开机失败现场: %v": "Instance %d: could not get the cleanup lock; still publishing the completed start failure snapshot: %v",
+ "实例 %d 后台应用清理未启动: %s": "Instance %d could not start the background app watcher: %s",
"实例 %d 回到轻量桌面失败: %s": "Instance %d: failed to go back to the lightweight launcher: %s",
"实例 %d 安卓已开机": "Instance %d: Android has booted",
"实例 %d 安卓已开机(%.1f 秒)": "Instance %d: Android has booted (%.1f s)",
@@ -387,6 +388,7 @@
"实例 %d 无法确认 SDK/adb 目标,本次不切换宿主采集: %v": "Instance %d: cannot determine the SDK/adb target; not switching host collection this time: %v",
"实例 %d 无法确认 SDK/adb 目标,本次不改客体缓冲区: %v": "Instance %d: cannot determine the SDK/adb target; not changing the guest buffer this time: %v",
"实例 %d 无法确认日志采集的 SDK/adb 目标,本次不新起采集: %v": "Instance %d: cannot determine the SDK/adb target for log collection; not starting a new collection this time: %v",
+ "实例 %d 无法读取应用保活设置,跳过后台应用清理: %v": "Instance %d could not read the background app setting, skipping cleanup: %v",
"实例 %d 显示设为 %d×%d、DPI %d、不显示导航栏(已写入 config.ini)": "Instance %d display set to %d×%d, DPI %d, no navigation bar (written to config.ini)",
"实例 %d 更新 arm64 执行桥": "Instance %d: updating the arm64 execution bridge",
"实例 %d 更新执行桥后关机再开机失败: %v": "Instance %d: shutting down and starting again after updating the execution bridge failed: %v",
diff --git a/internal/i18n/locales/en/mcp.json b/internal/i18n/locales/en/mcp.json
index bd38f2c..8dceb53 100644
--- a/internal/i18n/locales/en/mcp.json
+++ b/internal/i18n/locales/en/mcp.json
@@ -33,7 +33,7 @@
"已取消": "Canceled",
"收到的消息不是合法 JSON,已回复解析错误: %s": "The received message is not valid JSON; replied with a parse error: %s",
"新建中 %d%%:%s": "Creating %d%%: %s",
- "没有要改的选项:title、memory_mb、cpu、fps、resolution、dpi、orientation、data_partition_gb、data_disk_auto、sound 至少给一项": "No option to change: give at least one of title, memory_mb, cpu, fps, resolution, dpi, orientation, data_partition_gb, data_disk_auto, sound",
+ "没有要改的选项:title、memory_mb、cpu、fps、resolution、dpi、orientation、data_partition_gb、data_disk_auto、sound、app_keepalive 至少给一项": "No option to change: give at least one of title, memory_mb, cpu, fps, resolution, dpi, orientation, data_partition_gb, data_disk_auto, sound, app_keepalive",
"没有要改的:enabled、server、apps、add_apps、remove_apps 至少给一项": "Nothing to change: give at least one of enabled, server, apps, add_apps, remove_apps",
"确认要删除时把 confirm 设为 true": "To confirm the deletion, set confirm to true",
"等 %d 个正在写文件的请求做完再退出(最多 %.0f 秒)": "Waiting for %d requests that are writing files to finish before exiting (up to %.0f s)",
diff --git a/internal/i18n/locales/en/ui.json b/internal/i18n/locales/en/ui.json
index d309268..07c46ca 100644
--- a/internal/i18n/locales/en/ui.json
+++ b/internal/i18n/locales/en/ui.json
@@ -231,7 +231,7 @@
"老板键:读不了实例: %v": "Boss key: cannot read instances: %v",
"自定义组件下载源至少要有一个地址": "A custom component download source needs at least one address",
"至少给出 enabled、server、apps 中的一项": "Give at least one of enabled, server, apps",
- "至少给出 title、memory_mb、cpu、fps、resolution、dpi、orientation、data_partition_gb、data_disk_auto、language、time_zone、diagnostics、sound、boss_key 中的一项": "Give at least one of title, memory_mb, cpu, fps, resolution, dpi, orientation, data_partition_gb, data_disk_auto, language, time_zone, diagnostics, sound, boss_key",
+ "至少给出 title、memory_mb、cpu、fps、resolution、dpi、orientation、data_partition_gb、data_disk_auto、language、time_zone、diagnostics、sound、app_keepalive、boss_key 中的一项": "Give at least one of title, memory_mb, cpu, fps, resolution, dpi, orientation, data_partition_gb, data_disk_auto, language, time_zone, diagnostics, sound, app_keepalive, boss_key",
"补全 Google Play 商店": "setting up Google Play Store",
"补全组件": "fetching components",
"补全组件必须明确同意许可协议": "Fetching components requires explicitly accepting the license agreement",
diff --git a/internal/i18n/locales/en/web.json b/internal/i18n/locales/en/web.json
index 03e4b69..ed7e7f7 100644
--- a/internal/i18n/locales/en/web.json
+++ b/internal/i18n/locales/en/web.json
@@ -90,6 +90,7 @@
"上次补全组件没有成功:{reason}": "The last fetch of components failed: {reason}",
"上次设置为 {last_language},之后保留安卓里的修改。": "Last set to {last_language}; changes made inside Android are kept afterwards.",
"下次开机生效。MAA 等自动化任务要横屏,竖屏只适合自己玩": "Takes effect at the next start. Automation such as MAA needs landscape; portrait is for playing yourself",
+ "下次开机生效。关闭时,第三方应用退到后台满 60 秒后结束,切回前台会取消计时。": "Takes effect at the next boot. When off, third-party apps stop after 60 seconds in the background. Returning to an app cancels its timer.",
"下次开机生效,带窗口和无头都有声音。开了会多占一些 CPU。": "Takes effect at the next start; sound works with a window and headless. It uses some more CPU.",
"下次开机生效,自动化工具里的分辨率也要跟着改": "Takes effect at the next start; change the resolution in your automation tool as well",
"下次开机生效;跟随分辨率时 720p 是 240,1080p 是 280": "Takes effect at the next start; following the resolution is 240 at 720p and 280 at 1080p",
@@ -314,6 +315,7 @@
"已重新检查这台电脑。": "The computer was checked again.",
"帧率": "Frame rate",
"序列号": "Serial number",
+ "应用保活": "Keep background apps",
"应用名单": "App list",
"开关": "Switch",
"开启": "Turn on",
diff --git a/internal/mcp/mcp_test.go b/internal/mcp/mcp_test.go
index 6b96bfa..422d8de 100644
--- a/internal/mcp/mcp_test.go
+++ b/internal/mcp/mcp_test.go
@@ -1020,6 +1020,20 @@ func TestUpdateSound(t *testing.T) {
}
}
+func TestUpdateAppKeepalive(t *testing.T) {
+ h := newHarness(t, nil, nil)
+ h.initialize("2025-11-25")
+ for k, on := range []bool{true, false} {
+ h.send(fmt.Sprintf(`{"jsonrpc":"2.0","id":%d,"method":"tools/call","params":{"name":"update_instance","arguments":{"index":1,"app_keepalive":%v}}}`, k+2, on))
+ if text, isErr, _ := toolText(t, h.recv()); isErr {
+ t.Fatalf("app_keepalive %v: %s", on, text)
+ }
+ if u := h.f.updates[k]; u.AppKeepalive == nil || *u.AppKeepalive != on || u.MemoryMB != nil {
+ t.Fatalf("app_keepalive %v: update %+v", on, u)
+ }
+ }
+}
+
func TestServeNeedsManager(t *testing.T) {
err := Serve(context.Background(), strings.NewReader(""), io.Discard, Options{})
if errs.CodeOf(err) != errs.Internal {
diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go
index 98238f8..40da915 100644
--- a/internal/mcp/tools.go
+++ b/internal/mcp/tools.go
@@ -259,7 +259,7 @@ func toolDefs() []*toolDef {
})),
finishing(newTool("update_instance", "Update instance",
- "Change the title, memory, CPU cores, frame rate, resolution, DPI, orientation, data disk (a fixed size or automatic) or sound of an instance. The changes take "+
+ "Change the title, memory, CPU cores, frame rate, resolution, DPI, orientation, data disk (a fixed size or automatic), sound or background app retention of an instance. The changes take "+
"effect at its next boot (applies_next_boot=true when it is running now).",
mutating(true, true), reflect.TypeFor[emu.UpdateResult](), []prop{
indexProp(true),
@@ -277,6 +277,7 @@ func toolDefs() []*toolDef {
{"data_disk_auto", false, map[string]any{"type": "boolean", "description": fmt.Sprintf("true: make the data "+
"disk automatic (%d GB from the next boot, the host only pays for what is written). Not together with "+
"data_partition_gb.", avd.AutoDataPartitionGB)}},
+ {"app_keepalive", false, map[string]any{"type": "boolean", "description": "Keep background apps from the next boot. By default, a third-party app is stopped after 60 continuous seconds in the background. Home, the active keyboard, system apps and Google services are exempt."}},
{"sound", false, map[string]any{"type": "boolean", "description": "true: host sound and a guest sound " +
"card from the next boot, windowed or headless (costs some CPU); false: no sound (the default)."}},
},
@@ -315,12 +316,15 @@ func toolDefs() []*toolDef {
return nil, err
}
req.DataDiskAuto = auto != nil && *auto
+ if req.AppKeepalive, err = a.optBool("app_keepalive"); err != nil {
+ return nil, err
+ }
if req.Sound, err = a.optBool("sound"); err != nil {
return nil, err
}
if req.Title == nil && req.MemoryMB == nil && req.CPU == nil && req.FPS == nil && req.Resolution == nil && req.DPI == nil && req.Orientation == nil &&
- req.DataPartitionGB == nil && !req.DataDiskAuto && req.Sound == nil {
- return nil, errs.New(errs.Usage, "没有要改的选项:title、memory_mb、cpu、fps、resolution、dpi、orientation、data_partition_gb、data_disk_auto、sound 至少给一项")
+ req.DataPartitionGB == nil && !req.DataDiskAuto && req.Sound == nil && req.AppKeepalive == nil {
+ return nil, errs.New(errs.Usage, "没有要改的选项:title、memory_mb、cpu、fps、resolution、dpi、orientation、data_partition_gb、data_disk_auto、sound、app_keepalive 至少给一项")
}
return b.Update(ctx, i, req)
})),
diff --git a/internal/ui/API.en.md b/internal/ui/API.en.md
index 313c68d..1975a39 100644
--- a/internal/ui/API.en.md
+++ b/internal/ui/API.en.md
@@ -43,7 +43,7 @@ HTTP 4xx / 5xx with the body `{"error":{"code":"…","message":"…","advice":"
| GET | `/api/instances/{i}` | | `InstanceInfo` |
| GET | `/api/instances/{i}/regional` | | `RegionalResult` |
| POST | `/api/instances` | `{title?, index?, count?, memory_mb?, cpu?, data_partition_gb?, fps?, resolution?, dpi?, orientation?: string, language?: string, time_zone?: string}` | 202 `Job` (`kind` is `create`: without `data_partition_gb` the data disk is automatic (256 GB), with it a fixed size; it boots in the background, finishes the initial setup and shuts down again, which takes a few minutes. When `index` is not given, the server picks the number first, and `Job.index` is the new instance's; the result is an `InstanceInfo`). A new instance comes without the Google Play store (there is no `play_store` field; sending one returns 400). If you want it, use `playstore-install` below after the instance is created. `count` creates several at once (1–9, 1 when not given, not together with `index`): above 1 the server takes that many free numbers first (409 `busy` and nothing created when there are fewer), starts a `create` job for each at once and answers 202 `{jobs: [Job…]}`; the jobs run one after another in number order (a waiting one has `progress.step` `queued` and can be cancelled on its own), each checks the free space of the instances' disk before it starts and fails (`precheck_failed`) when it is too low; `title` gets a number (`T 1`, `T 2` …); one failing or cancelled does not stop the others |
-| PATCH | `/api/instances/{i}` | `{title?, memory_mb?, cpu?, fps?, resolution?, dpi?, orientation?: string, data_partition_gb?, data_disk_auto?: bool, diagnostics?: bool, sound?: bool, boss_key?: string, language?: string, time_zone?: string}` | `UpdateResult`; the diagnostics setting and the boss key take effect immediately, ordinary configuration (`sound` too) at the next boot. `data_partition_gb` gives the data disk a fixed size (only larger), `data_disk_auto: true` makes it automatic; not both. When `boss_key` is given, the result has one more field `boss_key_taken` (bool): the new key was tried at once, and `true` means another program holds it (see "Boss keys and the tray" below) |
+| PATCH | `/api/instances/{i}` | `{title?, memory_mb?, cpu?, fps?, resolution?, dpi?, orientation?: string, data_partition_gb?, data_disk_auto?: bool, diagnostics?: bool, sound?: bool, app_keepalive?: bool, boss_key?: string, language?: string, time_zone?: string}` | `UpdateResult`; the diagnostics setting and the boss key take effect immediately, ordinary configuration (including `sound` and `app_keepalive`) at the next boot. `data_partition_gb` gives the data disk a fixed size (only larger), `data_disk_auto: true` makes it automatic; not both. When `boss_key` is given, the result has one more field `boss_key_taken` (bool): the new key was tried at once, and `true` means another program holds it (see "Boss keys and the tray" below) |
| GET | `/api/instances/{i}/diagnostics/preview` | | `{"index","files","bytes"}`: the number of files and bytes that would be cleaned up when diagnostics is turned off; it changes no configuration and deletes no files |
| DELETE | `/api/instances/{i}?confirm=1` | without `confirm=1` the server returns 400 `usage` | `DeleteResult` |
| POST | `/api/instances/{i}/start` | `{}` | 202 `Job`: always boots with a window (the manager never boots headless; headless boot is command line only). If the instance is already running headless, the job fails with code `busy` (no switching while running) |
diff --git a/internal/ui/API.md b/internal/ui/API.md
index 9cd7b67..d27eed6 100644
--- a/internal/ui/API.md
+++ b/internal/ui/API.md
@@ -43,7 +43,7 @@ HTTP 4xx / 5xx,体为 `{"error":{"code":"…","message":"…","advice":"…","
| GET | `/api/instances/{i}` | | `InstanceInfo` |
| GET | `/api/instances/{i}/regional` | | `RegionalResult` |
| POST | `/api/instances` | `{title?, index?, count?, memory_mb?, cpu?, data_partition_gb?, fps?, resolution?, dpi?, orientation?: string, language?: string, time_zone?: string}` | 202 `Job`(`kind` 是 `create`:不给 `data_partition_gb` 是自动扩盘(256 GB),给了是指定大小;后台开机做完初始化再关机,要几分钟;没给 `index` 时服务端先选好编号,`Job.index` 就是新实例的;结果是 `InstanceInfo`)。新建的实例不带 Google Play 商店(没有 `play_store` 字段,给了回 400),要的话建好后用下面的 `playstore-install`。`count` 是一次建几台(1–9,不给是 1,不能和 `index` 一起给):大于 1 时服务端先取好这么多个空闲编号(不够就 409 `busy`,一台不建),每台当场开一个 `create` 任务,回 202 `{jobs: [Job…]}`;任务按编号一台做完再做下一台(排着的 `progress.step` 是 `queued`,可以单独取消),每台开建前查实例所在盘的剩余空间,不够那一台失败(`precheck_failed`);`title` 后面加序号(`T 1`、`T 2`…);一台失败或取消不影响别的 |
-| PATCH | `/api/instances/{i}` | `{title?, memory_mb?, cpu?, fps?, resolution?, dpi?, orientation?: string, data_partition_gb?, data_disk_auto?: bool, diagnostics?: bool, sound?: bool, boss_key?: string, language?: string, time_zone?: string}` | `UpdateResult`;诊断和老板键立即生效,普通配置(声音 `sound` 也是)下次开机生效。`data_partition_gb` 把数据盘改成指定大小(只能改大),`data_disk_auto: true` 改成自动扩盘,两个不能同时给。给了 `boss_key` 时多一个 `boss_key_taken`(bool):新键当场试注册过,被别的程序占着是 `true`(见下「老板键和托盘」) |
+| PATCH | `/api/instances/{i}` | `{title?, memory_mb?, cpu?, fps?, resolution?, dpi?, orientation?: string, data_partition_gb?, data_disk_auto?: bool, diagnostics?: bool, sound?: bool, app_keepalive?: bool, boss_key?: string, language?: string, time_zone?: string}` | `UpdateResult`;诊断和老板键立即生效,普通配置(包括 `sound` 和 `app_keepalive`)下次开机生效。`data_partition_gb` 把数据盘改成指定大小(只能改大),`data_disk_auto: true` 改成自动扩盘,两个不能同时给。给了 `boss_key` 时多一个 `boss_key_taken`(bool):新键当场试注册过,被别的程序占着是 `true`(见下「老板键和托盘」) |
| GET | `/api/instances/{i}/diagnostics/preview` | | `{"index","files","bytes"}`:关闭诊断时预计清理的份数、字节,不改配置、不删文件 |
| DELETE | `/api/instances/{i}?confirm=1` | 不带 `confirm=1` 回 400 `usage` | `DeleteResult` |
| POST | `/api/instances/{i}/start` | `{}` | 202 `Job`:一律带窗口开机(管理器不开无头的,无头开机只走命令行);实例要先装执行桥时,装桥这几次准备用的开机都无头,装好后正常关机,最后一次带窗口开机(同 `modavd start --window`);实例已经以无头方式在运行时,任务失败,code 是 `busy`(运行中不切换) |
diff --git a/internal/ui/handlers.go b/internal/ui/handlers.go
index 72338c7..a27c03e 100644
--- a/internal/ui/handlers.go
+++ b/internal/ui/handlers.go
@@ -210,14 +210,15 @@ func (s *server) handleUpdate(w http.ResponseWriter, r *http.Request) {
DataPartitionGB *int `json:"data_partition_gb"`
DataDiskAuto bool `json:"data_disk_auto"`
BossKey *string `json:"boss_key"`
+ AppKeepalive *bool `json:"app_keepalive"`
Sound *bool `json:"sound"`
}
if !decode(w, r, &body) {
return
}
if body.Title == nil && body.MemoryMB == nil && body.CPU == nil && body.FPS == nil && body.Resolution == nil && body.DPI == nil && body.Orientation == nil &&
- body.DataPartitionGB == nil && !body.DataDiskAuto && body.Diagnostics == nil && body.Sound == nil && body.BossKey == nil && body.Language == nil && body.TimeZone == nil {
- writeError(w, errs.New(errs.Usage, "没有要改的设置").WithAdvice("至少给出 title、memory_mb、cpu、fps、resolution、dpi、orientation、data_partition_gb、data_disk_auto、language、time_zone、diagnostics、sound、boss_key 中的一项"))
+ body.DataPartitionGB == nil && !body.DataDiskAuto && body.Diagnostics == nil && body.Sound == nil && body.AppKeepalive == nil && body.BossKey == nil && body.Language == nil && body.TimeZone == nil {
+ writeError(w, errs.New(errs.Usage, "没有要改的设置").WithAdvice("至少给出 title、memory_mb、cpu、fps、resolution、dpi、orientation、data_partition_gb、data_disk_auto、language、time_zone、diagnostics、sound、app_keepalive、boss_key 中的一项"))
return
}
release, err := s.beginInstanceAction(kindSettings, i)
@@ -230,7 +231,7 @@ func (s *server) handleUpdate(w http.ResponseWriter, r *http.Request) {
Language: body.Language, TimeZone: body.TimeZone,
FPS: body.FPS, Resolution: body.Resolution, DPI: body.DPI, Orientation: body.Orientation,
DataPartitionGB: body.DataPartitionGB, DataDiskAuto: body.DataDiskAuto,
- Diagnostics: body.Diagnostics, BossKey: body.BossKey, Sound: body.Sound})
+ Diagnostics: body.Diagnostics, BossKey: body.BossKey, Sound: body.Sound, AppKeepalive: body.AppKeepalive})
if err != nil {
writeError(w, err)
return
diff --git a/internal/ui/web/dev/mock.js b/internal/ui/web/dev/mock.js
index 8bb6d52..b888fe8 100644
--- a/internal/ui/web/dev/mock.js
+++ b/internal/ui/web/dev/mock.js
@@ -50,7 +50,7 @@ function mk(i, title, o = {}) {
ports: { console, adb: console + 1, grpc: console + 2 },
screencap: { shm: 'SHM_videmulator' + console, shm_ready: st === 'online' },
// o.disk: a size the user set (manual); without it 自动扩盘 (256 GB)
- config: { memory_mb: o.mem || 6144, cpu: o.cpu || 6, fps: o.fps || 60, data_partition_gb: o.disk || 256, data_disk_mode: o.disk ? 'manual' : 'auto', resolution: o.resolution || 720, width: o.resolution === 1080 ? 1920 : 1280, height: o.resolution === 1080 ? 1080 : 720, dpi: o.dpi || (o.resolution === 1080 ? 280 : 240), dpi_setting: o.dpi || 0, orientation: o.orientation || 'landscape', sound: !!o.sound },
+ config: { memory_mb: o.mem || 6144, cpu: o.cpu || 6, fps: o.fps || 60, data_partition_gb: o.disk || 256, data_disk_mode: o.disk ? 'manual' : 'auto', resolution: o.resolution || 720, width: o.resolution === 1080 ? 1920 : 1280, height: o.resolution === 1080 ? 1080 : 720, dpi: o.dpi || (o.resolution === 1080 ? 280 : 240), dpi_setting: o.dpi || 0, orientation: o.orientation || 'landscape', app_keepalive: !!o.app_keepalive, sound: !!o.sound },
initialized, launcher: initialized ? 'µLauncher' : '',
renderer: initialized ? (o.sw ? SWIFT : GPU) : '', software_renderer: !!o.sw,
path: `${ROOT}\\avd\\mas_${i}.avd`,
@@ -1013,7 +1013,7 @@ async function handle(url, init) {
Object.assign(inst.config, { orientation: body.orientation, width: w, height: inst.config.resolution });
applied.orientation = body.orientation;
}
- for (const k of ['memory_mb', 'cpu', 'fps', 'sound']) if (body[k] != null) { inst.config[k] = body[k]; applied[k] = body[k]; }
+ for (const k of ['memory_mb', 'cpu', 'fps', 'sound', 'app_keepalive']) if (body[k] != null) { inst.config[k] = body[k]; applied[k] = body[k]; }
// the data disk: 自动扩盘, or a size that can only grow
if (body.data_disk_auto && body.data_partition_gb != null) return errResp('invalid_argument', '数据盘只能二选一:自动扩盘,或者指定大小');
if (body.data_disk_auto) {
diff --git a/internal/ui/web/js/forms.js b/internal/ui/web/js/forms.js
index a434fa8..bbae9a2 100644
--- a/internal/ui/web/js/forms.js
+++ b/internal/ui/web/js/forms.js
@@ -235,6 +235,8 @@ export function openSettings(i, field) {
const initDiagnostics = inst0.diagnostics === true;
const title = h('input', { class: 'input', id: 's-title', maxlength: '40', autocomplete: 'off', value: initTitle, placeholder: defaultName(i) });
const diagnostics = h('input', { type: 'checkbox', id: 's-diagnostics', checked: initDiagnostics, 'aria-describedby': 's-diagnostics-h' });
+ const initKeepalive = cfg.app_keepalive === true;
+ const keepalive = h('input', { type: 'checkbox', id: 's-keepalive', checked: initKeepalive, 'aria-describedby': 's-keepalive-h' });
const initSound = cfg.sound === true;
const sound = h('input', { type: 'checkbox', id: 's-sound', checked: initSound, 'aria-describedby': 's-sound-h' });
const boss = bossKeyField(inst0.boss_key || '', () => dirty());
@@ -267,6 +269,8 @@ export function openSettings(i, field) {
disk.rows,
inputRow(t('声音'), h('span', { class: 'checkbox p-switch' }, sound),
hint(t('下次开机生效,带窗口和无头都有声音。开了会多占一些 CPU。'), 's-sound-h')),
+ inputRow(t('应用保活'), h('span', { class: 'checkbox p-switch' }, keepalive),
+ hint(t('下次开机生效。关闭时,第三方应用退到后台满 60 秒后结束,切回前台会取消计时。'), 's-keepalive-h')),
inputRow(t('诊断模式'), h('span', { class: 'checkbox p-switch' }, diagnostics),
hint(t('立即生效。历史日志上限 4 GiB、客体内存最多增加 48 MiB;日志可能包含账号信息,仅保存在本机。'), 's-diagnostics-h')),
boss.row,
@@ -284,6 +288,7 @@ export function openSettings(i, field) {
const out = {};
if (title.value.trim() !== initTitle) out.title = title.value.trim();
if (diagnostics.checked !== initDiagnostics) out.diagnostics = diagnostics.checked;
+ if (keepalive.checked !== initKeepalive) out.app_keepalive = keepalive.checked;
if (sound.checked !== initSound) out.sound = sound.checked;
if (boss.changed()) out.boss_key = boss.value();
if (regional) Object.assign(out, regional.changes());
diff --git a/scripts/test_app_keepalive_guest.sh b/scripts/test_app_keepalive_guest.sh
new file mode 100644
index 0000000..bb27636
--- /dev/null
+++ b/scripts/test_app_keepalive_guest.sh
@@ -0,0 +1,75 @@
+#!/system/bin/sh
+# Copyright 2026 jinghero
+# On an Android 14 guest: sh test_app_keepalive_guest.sh /path/to/modavd-app-keepalive.sh
+# Exercise the real mksh timers and logcat reader. No installed apps or settings are used.
+set -eu
+script=${1:?pass the guest watcher script}
+test -r "$script"
+scratch=$(mktemp -d /data/local/tmp/app-keepalive-test.XXXXXX)
+export scratch
+watcher=''
+cleanup() {
+ if [ -n "$watcher" ]; then kill "$watcher" 2>/dev/null || :; wait "$watcher" 2>/dev/null || :; fi
+ if [ -s "$scratch/logger" ]; then kill "$(cat "$scratch/logger")" 2>/dev/null || :; fi
+ rm -rf "$scratch"
+}
+trap cleanup EXIT
+trap 'exit 1' HUP INT TERM
+
+mkdir "$scratch/bin"
+cat >"$scratch/command" <<'STUB'
+#!/system/bin/sh
+case "${0##*/}" in
+ logcat)
+ [ ! -s "$scratch/logger" ] || exit 1
+ echo "$$" >"$scratch/logger"
+ exec tail -n +1 -f "$scratch/events" ;;
+ am)
+ case "$1" in
+ get-current-user) echo 0 ;;
+ force-stop) echo "$4" >>"$scratch/stopped" ;;
+ *) exit 1 ;;
+ esac ;;
+ pm)
+ for pkg do :; done
+ echo "$pkg" >"$scratch/query"
+ echo "package:$pkg" ;;
+ cmd) echo org.example.home/.Home ;;
+ settings) echo org.example.ime/.Service ;;
+ dumpsys)
+ if [ ! -f "$scratch/ready" ]; then
+ touch "$scratch/checked.$(cat "$scratch/query")"
+ exit 1
+ fi
+ echo 'topResumedActivity=ActivityRecord{123 u0 org.example.home/.Home t1}' ;;
+esac
+STUB
+chmod 700 "$scratch/command"
+for cmd in logcat am pm cmd settings dumpsys; do ln -s "$scratch/command" "$scratch/bin/$cmd"; done
+: >"$scratch/events"
+PATH="$scratch/bin:$PATH" sh "$script" watch &
+watcher=$!
+
+# Pause both apps. Make the foreground query fail when each original deadline expires.
+for pkg in org.example.game org.example.login; do
+ echo "I/wm_pause_activity: [0,123,$pkg/.Main,userLeaving=true,pauseBackTasks]" >>"$scratch/events"
+done
+limit=$((SECONDS + 80))
+while [ ! -e "$scratch/checked.org.example.game" ] || [ ! -e "$scratch/checked.org.example.login" ]; do
+ [ "$SECONDS" -lt "$limit" ] || { echo 'did not check both expired timers' >&2; exit 1; }
+ sleep 0.2
+done
+test ! -e "$scratch/stopped"
+
+# Login briefly resumes and leaves again: only the game is due on the retry.
+echo 'I/wm_set_resumed_activity: [0,org.example.login/.Main,bringingFoundTaskToFront]' >>"$scratch/events"
+echo 'I/wm_pause_activity: [0,123,org.example.login/.Main,userLeaving=true,pauseBackTasks]' >>"$scratch/events"
+touch "$scratch/ready"
+limit=$((SECONDS + 20))
+while [ ! -s "$scratch/stopped" ]; do
+ [ "$SECONDS" -lt "$limit" ] || { echo 'lost pending app after a query failure' >&2; exit 1; }
+ sleep 0.2
+done
+sleep 1
+test "$(cat "$scratch/stopped")" = org.example.game
+echo 'PASS: retried the background app and cancelled the old login timer'
diff --git a/scripts/test_create_cancel.mjs b/scripts/test_create_cancel.mjs
index 5994590..f34156b 100644
--- a/scripts/test_create_cancel.mjs
+++ b/scripts/test_create_cancel.mjs
@@ -239,8 +239,7 @@ const turn = () => new Promise(resolve => setImmediate(resolve));
test('settings has a diagnostic checkbox with limits, privacy and immediate application', async () => {
const h = await settingsHarness();
- // the diagnostics switch and the sound switch
- assert.deepEqual(descendants(h.settings.form).filter(x => x.type === 'checkbox').map(x => x.attrs.get('id')), ['s-sound', 's-diagnostics']);
+ assert.deepEqual(descendants(h.settings.form).filter(x => x.type === 'checkbox').map(x => x.attrs.get('id')), ['s-sound', 's-keepalive', 's-diagnostics']);
assert.equal(h.control('s-diagnostics').checked, true);
const text = h.settings.options.body.textContent;
for (const expected of ['历史日志上限 4 GiB', '客体内存最多增加 48 MiB', '账号信息', '仅保存在本机', '诊断设置立即生效']) assert.ok(text.includes(expected), text);
@@ -269,6 +268,16 @@ test('the sound switch is off by default and patches a boolean', async () => {
assert.deepEqual(h.requests, [{ method: 'PATCH', path: '/api/instances/3', body: { sound: true } }]);
});
+test('keep background apps defaults to off and sends a settings patch', async () => {
+ const h = await settingsHarness();
+ const control = h.control('s-keepalive');
+ assert.equal(control.checked, false);
+ control.checked = true;
+ h.settings.form.dispatch('change');
+ await h.submit();
+ assert.deepEqual(h.requests, [{ method: 'PATCH', path: '/api/instances/3', body: { app_keepalive: true } }]);
+});
+
test('diagnostic save displays the external capture warning from its result', async () => {
const h = await settingsHarness({ diagnostics: false, patch: async () => ({
instance: { index: 3, diagnostics: true }, warnings: ['已有其它程序采集 logcat,诊断模式未接管宿主采集'],