打开 App 支持指定活动 + 预设快捷入口 (v2.0.43)

用户要求:"打开应用工具支持打开活动,并预设几个比如微信对话,支付宝菜鸟"

## 打开"活动"(Activity)分三层

  · **只给包名** → 自己查它的 launcher activity(不用模型去记
    `com.tencent.mm.ui.LauncherUI` 这种名字,既没必要也容易记错)
  · **给包名 + activity** → **先直拉那个 Activity**(能直达指定页面);
    直拉失败就退回标准 launcher 方式 —— App 内部的 Activity 常常没导出,
    直接拉会被系统拒(`ActivityNotFoundException`)
  · **给预设 id / 关键词** → 走下面那张表的回退链

## 预设快捷入口(13 个)

    微信主界面 / 微信聊天列表 / 微信扫一扫 / 微信朋友圈 / 微信收付款
    支付宝主界面 / 支付宝扫一扫 / 支付宝付款码 / 支付宝卡包 / 支付宝菜鸟
    淘宝 / QQ / 抖音

用户说"打开微信聊天"、"开一下支付宝菜鸟"这种**带目的地**的要求时,
`action=shortcut` 直达那个页面,比只打开主界面省事。

### ★ 每个预设是一**串候选**,不是一个

因为深链 scheme 和 Activity 名字**都会随 App 版本变**。只赌一个的话,
用户那边 App 一升级就静默失效,而且报的还是笼统的"打不开",查起来很费劲。

所以每个预设按顺序试,第一个成的算:

    1. 深链(最稳,scheme 通常不变)
    2. 指定 Activity(有的页面有独立 Activity)
    3. 退回主界面(保证"至少把 App 打开了")

返回里 `how` 说明是**哪一层**成的(uri / direct / launcher)。

### ★ 诚实地说明这些 scheme 没法离线验证

我没法在没有真机 App 的情况下确认 `weixin://dl/chat` 一定进"聊天列表"、
`alipays://platformapi/startapp?appId=200011235` 一定开菜鸟。
这些值来自公开的深链惯例,**多数情况可用,但 App 大版本更新后可能失效**。

所以设计上做了兜底:
  · 全部走"多候选 + 退回主界面" —— 失效也不会变成"点了没反应"
  · 失败时返回**试过哪些候选 + 各自为什么失败**,而不是一句"打不开"
  · 错误里带 hint 说明怎么改成自己手机上的值

## 实测(模拟器上没装微信/支付宝,正好测失败路径)

 · 列出 13 个预设,`installed` 标记正确
 · 用关键词找预设:`微信聊天` → 微信·聊天列表;`朋友圈`;`菜鸟` → 支付宝·菜鸟裹裹;
   `支付宝扫一扫`;`抖音` —— 全都能找到对的
 · 播不用装 App 的路径:只给包名打开 → `how=launcher act=com.android.launcher3.Launcher` ✓
 · **失败路径**:错误是
   `「微信 · 朋友圈」的所有打开方式都没成功;试过:uri()=没装这个 App,uri()=没装…`
   —— 说清了试过哪些、为什么,而不是笼统的"打不开" ✓
 · 不存在的预设 → 列出可用的 id ✓

## 顺带修的

 · `apps` 工具原来没把 `how` / `activity` 透传给模型 —— 这两个字段正是
   排查"为什么没进到我要的页面"的关键,丢了就只能看到一句"已打开"
 · 直拉和退回**都失败**时,错误里原来只说直拉那个原因,会误导
   (让人以为是 activity 名字写错,其实退回主界面也失败了 —— 后者更严重)
 · Kotlin 可见性坑连踩两次:`run()` 的参数类型不能是 private,改成 internal
   还是不行(public 函数不能暴露 internal 类型),最后用默认 public。
   报错是 `Function 'public' exposes its 'private-in-class' return type`。
 · `AppShortcuts.all()` 第一版用 `@Volatile var appCtx: Context?` 存上下文,
   编译期就是 `Context?`,每次用都要解包、还容易忘了赋值。
   改成**传参**,编译期就保证有。
This commit is contained in:
doubao
2026-10-15 16:36:17 +08:00
parent 74c87686ef
commit f330af963a
7 changed files with 600 additions and 14 deletions

View File

@@ -0,0 +1,128 @@
"""测「预设快捷入口」+ 打开 Activity。
★ 关键测的是**回退链**:深链失败 → 退回主界面,而不是"点了没反应"。
emulator 上没装微信/支付宝,所以正好能测"没装"那条路。
同时用**装了的 App** 测正常路径(图库 / 设置 / 浏览器)。
"""
import json
import sys
import urllib.error
import urllib.request
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
URL = "http://127.0.0.1:15199"
fails = []
def call(path, payload=None, method="POST", timeout=90):
data = json.dumps(payload, ensure_ascii=False).encode("utf-8") if payload is not None else None
req = urllib.request.Request(
URL + path, data=data, method=method,
headers={"Content-Type": "application/json; charset=utf-8"},
)
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode("utf-8"))
except urllib.error.HTTPError as e:
return json.loads(e.read().decode("utf-8", "replace"))
def tool(name, args):
return call("/api/tools/run", {"name": name, "args": args})
def err_of(r):
if not isinstance(r, dict):
return ""
return str(r.get("error") or (r.get("result") or {}).get("error") or "")
def check(cond, label, detail=""):
print(f" {'✓' if cond else '✗'} {label}" + (f" {detail}" if detail else ""))
if not cond:
fails.append(label)
print("=== 1. 列出预设 ===")
r = tool("apps", {"action": "shortcuts"})
res = (r or {}).get("result") or {}
items = res.get("shortcuts") or []
check(len(items) >= 10, f"有 {len(items)} 个预设")
for it in items[:6]:
mark = "装了" if it.get("installed") else "没装"
print(f" [{mark}] {it.get('id'):18s} {it.get('label')}")
print()
print("=== 2. 预设里要有用户点名的那两个 ===")
ids = [it.get("id") for it in items]
labels = " ".join(it.get("label") or "" for it in items)
check("wechat-chat" in ids, "有「微信 · 聊天列表」", "wechat-chat")
check("alipay-cainiao" in ids, "有「支付宝 · 菜鸟裹裹」", "alipay-cainiao")
check("菜鸟" in labels, "菜鸟那个标签里有「菜鸟」二字")
check("扫一扫" in labels, "也有扫一扫这类常用的")
print()
print("=== 3. ★ 用关键词找预设(用户会说「打开微信聊天」)===")
for kw in ("微信聊天", "朋友圈", "菜鸟", "支付宝扫一扫", "抖音"):
r = tool("apps", {"action": "shortcut", "shortcut": kw})
res = (r or {}).get("result") or {}
err = err_of(r)
if res.get("opened"):
check(True, f"「{kw}」→ {res.get('label')}", f"how={res.get('how')}")
else:
# 没装这些 App,所以必然失败 —— 但**必须是"没装"这种可解释的失败**
check("没装" in err or "没成功" in err, f"「{kw}」失败但理由可解释", err[:80])
print()
print("=== 4. ★★ 失败时必须说明「试过哪些、各自为什么失败」 ===")
r = tool("apps", {"action": "shortcut", "shortcut": "朋友圈"})
err = err_of(r)
check("试过" in err, "错误里列出了试过哪些候选", err[:110])
check("没装" in err, "说清了是没装(而不是笼统的'打不开')")
check("hint" in json.dumps(r, ensure_ascii=False) or "action=open" in err,
"给了下一步建议")
print()
print("=== 5. 不存在的预设要给可选项 ===")
r = tool("apps", {"action": "shortcut", "shortcut": "根本不存在的预设xyz"})
err = err_of(r)
check("没有叫" in err, "说清了没有这个预设", err[:70])
check("wechat" in err or "可以用的有" in err, "列出了可用的预设")
print()
print("=== 6. 打开 Activity:只给包名也能开(自己查 launcher activity)===")
r = tool("apps", {"action": "list"})
res = (r or {}).get("result") or {}
apps = res.get("apps") or []
if apps:
pkg = apps[0].get("package")
r2 = tool("apps", {"action": "open", "package": pkg})
res2 = (r2 or {}).get("result") or {}
check(bool(res2.get("opened")) or bool(err_of(r2)),
f"用包名打开 {pkg}", f"how={res2.get('how')} act={res2.get('activity')}")
check(bool(res2.get("activity")) or bool(err_of(r2)),
"返回了自己查到的 activity 名", str(res2.get("activity"))[:60])
print()
print("=== 7. 给了 activity 就直达(activity 没导出时退回主界面)===")
if apps:
pkg = apps[0].get("package")
r3 = tool("apps", {"action": "open", "package": pkg, "activity": pkg + ".NoSuchActivity"})
res3 = (r3 or {}).get("result") or {}
err3 = err_of(r3)
if res3.get("opened"):
check(True, "坏 activity 名 → 自动退回主界面", f"how={res3.get('how')} note={res3.get('note')}")
else:
check(bool(err3), "或者如实报错", err3[:80])
print()
if fails:
print(f"❌ {len(fails)} 项不合格:")
for f in fails:
print(" -", f)
sys.exit(1)
print("✅ 全部通过")