Procházet zdrojové kódy

修复卡片更新

chendeben před 1 rokem
rodič
revize
56f2bcfc67

+ 79 - 0
entry/src/main/ets/common/widget/WidgetRegistrationFix.ets

@@ -0,0 +1,79 @@
+import { hilog } from '@kit.PerformanceAnalysisKit';
+import { Context } from '@kit.AbilityKit';
+import { PreferencesUtil } from '../utils/PreferencesUtil';
+import { GlobalWidgetManager } from './GlobalWidgetManager';
+
+const TAG = 'WidgetRegistrationFix';
+
+/**
+ * 卡片注册修复工具
+ * 用于修复卡片注册和持久化问题
+ */
+export class WidgetRegistrationFix {
+  private static instance: WidgetRegistrationFix | null = null;
+  private preferencesUtil: PreferencesUtil = PreferencesUtil.getInstance();
+  private globalWidgetManager: GlobalWidgetManager = GlobalWidgetManager.getInstance();
+
+  private constructor() {}
+
+  public static getInstance(): WidgetRegistrationFix {
+    if (!WidgetRegistrationFix.instance) {
+      WidgetRegistrationFix.instance = new WidgetRegistrationFix();
+    }
+    return WidgetRegistrationFix.instance;
+  }
+
+  /**
+   * 执行卡片注册修复
+   */
+  public async fixWidgetRegistration(context: Context): Promise<void> {
+    try {
+      hilog.info(0x0000, TAG, '🔧 开始卡片注册修复...');
+      
+      // 同步活跃卡片到持久化存储
+      await this.syncActiveWidgetsToPersistence(context);
+      
+      hilog.info(0x0000, TAG, '✅ 卡片注册修复完成');
+      
+    } catch (error) {
+      hilog.error(0x0000, TAG, `❌ 卡片注册修复失败: ${error}`);
+    }
+  }
+
+
+
+  /**
+   * 同步活跃卡片到持久化存储
+   */
+  private async syncActiveWidgetsToPersistence(context: Context): Promise<void> {
+    try {
+      const prefs = await this.preferencesUtil.getPreferences(context);
+      const persistedIds = await this.preferencesUtil.getFormIds(prefs);
+      const activeWidgets = this.globalWidgetManager.getActiveWidgets();
+      const activeIds = Array.from(activeWidgets.keys());
+      
+      hilog.info(0x0000, TAG, `📊 持久化: ${persistedIds.length}个, 活跃: ${activeIds.length}个`);
+      
+      // 将活跃但未持久化的卡片添加到持久化存储
+      const missingInPersistence = activeIds.filter(id => !persistedIds.includes(id));
+      if (missingInPersistence.length > 0) {
+        hilog.info(0x0000, TAG, `🔧 同步 ${missingInPersistence.length} 个活跃卡片到持久化存储`);
+        
+        // 串行处理,避免并发问题
+        for (const formId of missingInPersistence) {
+          try {
+            await this.preferencesUtil.addFormId(prefs, formId);
+            hilog.info(0x0000, TAG, `✅ 同步卡片成功: ${formId}`);
+          } catch (error) {
+            hilog.error(0x0000, TAG, `❌ 同步卡片失败 ${formId}: ${error}`);
+          }
+        }
+      }
+      
+    } catch (error) {
+      hilog.error(0x0000, TAG, `❌ 同步活跃卡片失败: ${error}`);
+    }
+  }
+
+
+}

+ 19 - 0
entry/src/main/ets/entryability/EntryAbility.ets

@@ -18,6 +18,7 @@ import { rpc } from '@kit.IPCKit';
 import { Utility } from '../common/util/Utility';
 import { WXApi, WXEventHandler } from '../common/util/WXApiWrap';
 import { UnifiedPlayerService } from '../common/service/UnifiedPlayerService';
+import { WidgetRegistrationFix } from '../common/widget/WidgetRegistrationFix';
 
 import { systemShare } from '@kit.ShareKit';
 import { SpiderMan } from '@simplepeng/spider-man';
@@ -118,6 +119,9 @@ export default class EntryAbility extends UIAbility {
             hilog.error(0x0000, 'Heanup2', `❌ Failed to initialize UnifiedPlayerService: ${error}`);
         }
 
+        // 执行卡片注册修复(异步执行,不阻塞启动)
+        this.fixWidgetRegistrationAsync();
+
         setTimeout(async ()=>{
             this.loadDoWant(want)
             await this.handleParam(want)
@@ -492,4 +496,19 @@ export default class EntryAbility extends UIAbility {
             hilog.error(0x0000, 'Heanup2', `❌ Failed to process widget control command: ${error}`);
         }
     }
+
+    /**
+     * 异步执行卡片注册修复
+     */
+    private async fixWidgetRegistrationAsync(): Promise<void> {
+        // 延迟3秒执行,确保应用完全启动
+        setTimeout(async () => {
+            try {
+                const widgetFix = WidgetRegistrationFix.getInstance();
+                await widgetFix.fixWidgetRegistration(this.context);
+            } catch (error) {
+                hilog.error(0x0000, 'Heanup2', `❌ 卡片注册修复失败: ${error}`);
+            }
+        }, 3000);
+    }
 }

+ 22 - 2
entry/src/main/ets/entryformability/EntryFormAbility.ets

@@ -478,6 +478,8 @@ implements SizeChangeListener {
     // 持久化保存 Form ID(异步执行,不阻塞返回)
     this.saveFormIdToPersistence(formId).then(() => {
       hilog.info(0x0000, TAG, `💾 Form ID persistence completed for: ${formId}`);
+    }).catch(() => {
+      hilog.error(0x0000, TAG, `❌ Form ID persistence failed for ${formId}`);
     })
 
     // 检测卡片尺寸并注册到全局管理器
@@ -939,10 +941,28 @@ implements SizeChangeListener {
       hilog.info(0x0000, TAG, `💾 Saving Form ID to persistence: ${formId}`);
       const preferencesUtil = PreferencesUtil.getInstance();
       const prefs = await preferencesUtil.getPreferences(this.context);
+      
+      // 先检查是否已存在,避免重复添加
+      const existingIds = await preferencesUtil.getFormIds(prefs);
+      if (existingIds.includes(formId)) {
+        hilog.info(0x0000, TAG, `💾 Form ID already exists: ${formId}`);
+        return;
+      }
+      
+      hilog.info(0x0000, TAG, `💾 Current persisted IDs before adding: [${existingIds.join(', ')}]`);
+      
       await preferencesUtil.addFormId(prefs, formId);
-      hilog.info(0x0000, TAG, `✅ Form ID saved successfully: ${formId}`);
+      
+      // 简化验证,只检查是否添加成功
+      const updatedIds = await preferencesUtil.getFormIds(prefs);
+      if (updatedIds.includes(formId)) {
+        hilog.info(0x0000, TAG, `✅ Form ID saved successfully: ${formId}`);
+      } else {
+        hilog.warn(0x0000, TAG, `⚠️ Form ID save verification failed, but continuing: ${formId}`);
+      }
     } catch (error) {
-      hilog.error(0x0000, TAG, `❌ Failed to save Form ID: ${error}`);
+      hilog.error(0x0000, TAG, `❌ Failed to save Form ID ${formId}: ${error}`);
+      // 不再抛出错误,避免阻塞卡片创建
     }
   }