用户三条:
① "还可以发送通知"
② "太挤了对话都没了"(抽屉截图圈出整片区域)
③ "还是没有读到"(读通知)
## ① 发通知(新能力)
`notifications` 工具加了 `action=notify`,传 title / text 就发一条。
点了通知会回到本 App(`PendingIntent`,不给的话点了没反应,
用户会觉得"这通知是死的")。
### ★★ 踩到一个"看起来成功其实没发出去"的坑
第一版发通知返回 `{"sent": true}`,但通知栏里**什么都没有**。查 dumpsys 才看到:
AppSettings: com.doubao.lynxclone importance=NONE ← App 级被关了
NotificationChannel{mId='doubao_ai', mImportance=3} ← 渠道建出来了
**Android 13(API 33) 起 `POST_NOTIFICATIONS` 是运行时权限,新装的 App 默认拒绝。**
不申请的话 `notify()` 不报错、但通知根本不显示。
修法:
· Manifest 声明 `POST_NOTIFICATIONS`(外加 `VIBRATE`,通知声音/震动要它)
· MainActivity 在 33+ 运行时 `requestPermissions`
· 实测:`pm grant` 之后 AppSettings 变成 `importance=DEFAULT`,通知立刻正常显示
另外几个细节:
· Android 8+ **必须挂渠道**,否则通知被直接丢掉(连报错都没有)
· 渠道重要性用 DEFAULT:太低会被折叠成静音(用户注意不到),
HIGH 会弹横幅(对"AI 提醒你一件事"太打扰)
· 用时间戳当通知 id:固定 id 的话后一条会把前一条顶掉
· 不给 `setSmallIcon` 通知**不会显示**(用 app 自己的图标)
## ② 抽屉重排(用户:"太挤了对话都没了")
原来平铺 9 个入口,把底下的**对话列表**挤得只剩一条 ——
而对话列表恰恰是抽屉最主要的功能(用户 90% 打开抽屉是为了切对话)。
现在:
· 第一层只放**天天用的**:功能分区(新话题 / 智能体 / 笔记 / 模型 / 更多功能)
· 「更多功能」点开是独立全屏页:AI 界面 / 技能连接器 / 会议模式 / 终端 / 设置
· 对话列表分区标题从「置顶」改成「对话」(它列的是全部对话,不只置顶的)
按项目约定用**独立全屏页**而不是折叠面板:折叠每次都要展开一次,反而更麻烦。
## ③ 读通知"还是没有读到" —— 根因是只在内存里记
查下去:权限是开的、服务也连着(日志 `通知使用权已连接`),
问题是第一版**只在 `onNotificationPosted` 里记** —— 也就是
**只有本进程活着那段时间收到的通知才算数**。进程一重启
(升级 App、系统杀后台)内存就空了,之前的通知全看不到。
用户的期望是"读我手机上**现在**的通知" —— 那本来就该包含
**在他打开 App 之前就收到的那些**。
修法:加 `syncActive()`,用 `NotificationListenerService.getActiveNotifications()`
把系统当前挂着的通知同步进来。两处调用:
· `onListenerConnected()` —— 连上的瞬间同步一次(不然装完 App 立刻问是空的)
· `recent()` 每次读之前再同步一次
★ 为此要在 companion 里存一个 service 实例引用(`getActiveNotifications()`
是 service 自己的方法,不是静态的),并把 `record()` 从 private 改成 internal
(Kotlin 的 private 只对同一个类体可见,伴生对象不算)。
★ 顺手过滤掉**标题正文都空的**通知(媒体控制、下载进度这类,
文字在 RemoteViews 里取不到)。留着的话用户会看到"什么都没有"的条目,纯噪音。
实测(关键:App 完全没在跑的时候发通知,再启动去读):
启动前发的「短信 你的验证码是 8842」「微信 张伟: 晚上吃饭吗」都读到了,
连 **5 小时前**那条系统通知也读到了。修复前这些全是空的。
193 lines
7.7 KiB
Python
193 lines
7.7 KiB
Python
"""读手机上的通知。
|
||
|
||
## 这是三个"动手机"的工具之一(另两个:开 App、调音量)
|
||
|
||
## ★ 隐私:读到的内容可能很敏感
|
||
|
||
通知里有验证码、银行短信、私信 —— 这是**整个 App 里最隐私的一类数据**。
|
||
所以:
|
||
|
||
· 只在**内存**里留最近 200 条,不落盘(进程一死就没了)。
|
||
写磁盘意味着卸载前一直躺着,也可能被别的工具读到。
|
||
· 用户要在系统设置里**手动开"通知使用权"**才能读到。
|
||
Android 没有这个权限的运行时申请弹窗 —— 这是唯一合法的路。
|
||
· 读之前一定先查权限,没开就**明确报错**(见下)。
|
||
|
||
## ★ 权限没开时返回错误,不是空列表
|
||
|
||
返回空列表的话模型会说"你最近没有通知" —— 那是**错的**
|
||
(明明有好几条,只是我们读不到)。用户会被误导,
|
||
而且他不会想到"原来是要去开个权限"。
|
||
|
||
所以这里返回一个带 `hint` 的错误,模型就能照着告诉用户怎么开。
|
||
"""
|
||
|
||
import os
|
||
import sys
|
||
|
||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||
from _protocol import serve # noqa: E402
|
||
from _ui_bridge import call_device # noqa: E402
|
||
|
||
TOOL = {
|
||
"name": "notifications",
|
||
"description": (
|
||
"读手机上的通知,或者**主动发一条通知**给用户。"
|
||
"\n\n读:"
|
||
"\n· action=list(默认)—— 列出最近的通知。"
|
||
"query 可以按关键词过滤(标题/正文/App 名),limit 默认 20、最多 200。"
|
||
"\n· action=alive —— 只看**还挂在通知栏上**的(已经被用户划掉的不算)"
|
||
"\n· action=access —— 查有没有「通知使用权」"
|
||
"\n· action=open_settings —— 跳到系统的通知使用权设置页,让用户去开"
|
||
"\n· action=clear —— 把已经读到的记录清掉(内存里那份)"
|
||
"\n\n发:"
|
||
"\n· action=notify —— 发一条通知给用户。传 title(标题)和 text(正文)。"
|
||
"\n ★ 这是**会打扰用户**的动作(他手机会响/震)——只在真的值得提醒时用:"
|
||
"\n 定时提醒、长任务跑完了、用户让你过一会儿告诉他。"
|
||
"\n 别用它来重复你已经在对话里说过的话。"
|
||
"\n 点了通知会回到本 App。"
|
||
"\n\n★ 读通知之前用户必须先手动开「通知使用权」(安卓不给运行时申请)。"
|
||
"\n 没开的时候本工具会返回错误 + 怎么开的提示 —— 请照着念给用户,"
|
||
"\n 别自己编步骤。**发通知不需要这个权限。**"
|
||
),
|
||
"parameters": {
|
||
"type": "object",
|
||
"properties": {
|
||
"action": {
|
||
"type": "string",
|
||
"enum": ["list", "alive", "access", "open_settings", "clear", "notify"],
|
||
"description": "要做的事,默认 list",
|
||
},
|
||
"query": {"type": "string", "description": "按关键词过滤(可选)"},
|
||
"limit": {"type": "number", "description": "最多几条,默认 20,最多 200"},
|
||
"title": {"type": "string", "description": "action=notify 时的通知标题"},
|
||
"text": {"type": "string", "description": "action=notify 时的通知正文"},
|
||
},
|
||
},
|
||
}
|
||
|
||
|
||
def run(args: dict) -> dict:
|
||
action = str(args.get("action") or "list").strip().lower()
|
||
|
||
# ★ 发通知放在最前面:它**不需要**通知使用权(那权限只管读),
|
||
# 所以不能被下面读路径的权限检查拦住。
|
||
if action == "notify":
|
||
title = str(args.get("title") or "").strip()
|
||
text = str(args.get("text") or "").strip()
|
||
if not title and not text:
|
||
raise ValueError("notify 至少要给 title 或 text")
|
||
res = call_device({
|
||
"action": "notification_post",
|
||
"title": title,
|
||
"text": text,
|
||
"autoCancel": True,
|
||
})
|
||
if res.get("unavailable"):
|
||
raise RuntimeError(res.get("error") or "当前环境没有通知能力")
|
||
if res.get("error"):
|
||
raise RuntimeError(str(res["error"]))
|
||
return {
|
||
"sent": True,
|
||
"title": res.get("title") or title,
|
||
"chars": res.get("chars", len(text)),
|
||
"note": (
|
||
"通知已经发出去了,用户手机会响/震一下。"
|
||
"点它会回到本 App。"
|
||
"**别为了同一件事再发一条** —— 用户会烦。"
|
||
),
|
||
}
|
||
|
||
if action == "open_settings":
|
||
res = call_device({"action": "notification_settings"})
|
||
if res.get("unavailable"):
|
||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||
if res.get("error"):
|
||
raise RuntimeError(str(res["error"]))
|
||
return {
|
||
"opened": True,
|
||
"note": (
|
||
"已经跳到系统的「通知使用权」设置页。"
|
||
"请让用户在那里找到本 App 并打开开关 —— 开了之后我才能读到通知。"
|
||
),
|
||
}
|
||
|
||
if action == "access":
|
||
res = call_device({"action": "notification_access"})
|
||
if res.get("unavailable"):
|
||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||
granted = bool(res.get("granted"))
|
||
out = {"granted": granted, "kept": res.get("kept", 0)}
|
||
if not granted:
|
||
out["note"] = (
|
||
"还没开「通知使用权」,读不到任何通知。"
|
||
"让用户去 设置 → 通知 → 通知使用权 里打开本 App(我也可以调 "
|
||
"action=open_settings 直接跳过去)。"
|
||
)
|
||
return out
|
||
|
||
if action == "clear":
|
||
res = call_device({"action": "notification_clear"})
|
||
if res.get("error"):
|
||
raise RuntimeError(str(res["error"]))
|
||
return {"cleared": True}
|
||
|
||
# list / alive
|
||
payload = {
|
||
"action": "notifications",
|
||
"query": str(args.get("query") or ""),
|
||
"onlyAlive": action == "alive",
|
||
}
|
||
try:
|
||
limit = int(args.get("limit") or 20)
|
||
except (TypeError, ValueError):
|
||
limit = 20
|
||
payload["limit"] = max(1, min(200, limit))
|
||
|
||
res = call_device(payload)
|
||
if res.get("unavailable"):
|
||
raise RuntimeError(res.get("error") or "当前环境没有界面能力")
|
||
|
||
# ★ 权限没开:把错误和"怎么开"一起抛回去。
|
||
# 抛异常而不是返回空列表 —— 空列表会让模型说"你没有通知",那是错的。
|
||
if res.get("error"):
|
||
hint = res.get("hint") or ""
|
||
raise RuntimeError(f"{res['error']}。{hint}".strip())
|
||
|
||
items = res.get("notifications") or []
|
||
# 顺手整理成模型好读的形状:把时间戳变成"几分钟前"
|
||
simplified = []
|
||
import time
|
||
now_ms = int(time.time() * 1000)
|
||
for n in items:
|
||
at = int(n.get("at") or 0)
|
||
ago = ""
|
||
if at:
|
||
secs = max(0, (now_ms - at) // 1000)
|
||
if secs < 60:
|
||
ago = "刚刚"
|
||
elif secs < 3600:
|
||
ago = f"{secs // 60} 分钟前"
|
||
elif secs < 86400:
|
||
ago = f"{secs // 3600} 小时前"
|
||
else:
|
||
ago = f"{secs // 86400} 天前"
|
||
simplified.append({
|
||
"app": n.get("app") or n.get("package") or "",
|
||
"title": n.get("title") or "",
|
||
"text": n.get("text") or "",
|
||
"ago": ago,
|
||
# 已经被划掉的也留着 —— 用户问"刚才那条验证码呢"时它早就没了
|
||
"gone": bool(n.get("removed")),
|
||
})
|
||
|
||
return {
|
||
"count": len(simplified),
|
||
"only_alive": action == "alive",
|
||
"notifications": simplified,
|
||
}
|
||
|
||
|
||
if __name__ == "__main__":
|
||
serve(TOOL, run)
|