从最新日志分析发现了真正的问题:
日志显示有多个不同的进程:
9103-9103 - 卡片进程18980-8980 - 主应用进程9738-9738 - 卡片进程2关键发现:每个进程都有自己的 GlobalWidgetManager 实例!
08-09 10:20:20.972 I Heanup widget global listener received state update: isPlaying=true, widgets count:
注意 widgets count: 后面是空的,说明 GlobalWidgetManager.getInstance().getActiveWidgetCount() 在某些进程中返回了 undefined。
activeWidgets: 3activeWidgets: 0(因为是不同的GlobalWidgetManager实例)不再依赖 GlobalWidgetManager 的跨进程状态同步,每个进程只管理自己的卡片。
// 旧代码(有问题)
const activeWidgetCount = GlobalWidgetManager.getInstance().getActiveWidgetCount();
if (activeWidgetCount > 0) {
this.updateAllWidgetsWithData(data);
}
// 新代码(修复)
hilog.info(0x0000, TAG, `Heanup widget global listener received state update: isPlaying=${data.playState.isPlaying}, process: ${process.pid}`);
// 总是尝试更新,让updateAllWidgetsWithData自己检查
this.updateAllWidgetsWithData(data);
添加进程ID到日志中,便于调试多进程问题:
hilog.info(0x0000, TAG, `Heanup widget updateAllWidgetsWithData called, active widgets: ${activeWidgets.size}, process: ${process.pid}`);
updateAllWidgetsWithData 自己决定是否有卡片需要更新I Heanup widget global listener received state update: isPlaying=true, process: 9738
I Heanup widget updateAllWidgetsWithData called, active widgets: 1, process: 9738
I Heanup widget 1952361985 calling formProvider.updateForm with isPlaying=true
I Heanup widget 1952361985 updated successfully: isPlaying=true
1. 主应用状态变化
2. 通过CommonEvent广播到所有进程
3. 每个卡片进程的全局监听器接收更新
4. 每个进程更新自己管理的卡片
5. 所有卡片都得到正确更新
这个修复解决了多进程环境下的状态同步问题,让每个进程独立管理自己的卡片,避免了跨进程状态依赖的复杂性。