chendeben 1 năm trước cách đây
mục cha
commit
47f427e983

+ 38 - 17
entry/src/main/ets/common/service/UnifiedPlayerService.ets

@@ -2837,7 +2837,7 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
       let successCount = 0;
       let failedCount = 0;
       const invalidFormIds: string[] = [];
-      let flatWidgetData = this.getWidgeFormData();
+      let flatWidgetData = this.getWidgetFormData();
       if (flatWidgetData) {
         // 逐个更新所有卡片
         for (const formId of formIds) {
@@ -2848,18 +2848,10 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
           } catch (error) {
             failedCount++;
             const errorStr: string = error?.toString() || '';
+            invalidFormIds.push(formId);
+            LogUtils.getInstance()
+              .LOGI(`UnifiedPlayerService updateAllForms: Form ${formId} - ${errorStr}}`);
 
-            // 检查是否是Form ID不存在的错误,并且增加更严格的判断条件
-            if ((errorStr.includes('does not exist') || errorStr.includes('不存在')) &&
-              !errorStr.includes('timeout') && !errorStr.includes('busy')) {
-              // 只有明确是"不存在"错误且不是临时性错误时才标记为无效
-              invalidFormIds.push(formId);
-              LogUtils.getInstance()
-                .LOGI(`UnifiedPlayerService updateAllForms: Form ${formId} does not exist, will be removed from storage`);
-            } else {
-              LogUtils.getInstance()
-                .LOGI(`UnifiedPlayerService updateAllForms: Failed to update form ${formId}: ${error} (not marking as invalid)`);
-            }
           }
 
           // 自动清理无效的Form ID
@@ -2884,7 +2876,7 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
     }
   }
 
-  public async getWidgeFormData(): Promise<widgeData | undefined> {
+  public async getWidgetFormData(): Promise<widgeData | undefined> {
     let imgMap: Record<string, number> = {};
     this.updatePlaylistStateInModelSync();
     const now = Date.now();
@@ -2894,10 +2886,7 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
     const songState: PlayerState = this.getCurrentState(); // PlayerState
     // 从持久化存储获取所有formId
     const context = AppStorage.get('context') as common.UIAbilityContext;
-    if (!context) {
-      LogUtils.getInstance().LOGI('UnifiedPlayerService updateAllForms: No context available');
-      return undefined;
-    }
+
 
     // 构建卡片数据,包含VideoItem和PlayerState信息
     const widgetPlayerState: WidgetPlayerState = {
@@ -2922,6 +2911,38 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
       progressPercentage: this.calculateProgressPercentage(songState.currentPosition || 0, songState.duration || 0)
     };
 
+    if (!context || !formData) {
+      const defaultData: widgeData = {
+        id: '',
+        name: '未知歌曲',
+        artist: '未知艺术家',
+        album: '未知专辑',
+        pixelMapPath: '',
+        duration: 0,
+        filePath: '',
+        imgName: '',
+        imageColorHex: '2A2A2A',
+        isPlaying: false,
+        isPaused: true,
+        isLoading: false,
+        hasNext: false,
+        hasPrevious: false,
+        isFavorite: false,
+        currentPosition: 0,
+        playMode: 0,
+        currentIndex: 0,
+        totalCount: 0,
+        currentTimeText: '',
+        totalTimeText: '',
+        progressPercentage: 0,
+        playerState: widgetPlayerState,
+        playlistInfo: widgetPlaylistInfo,
+        timeInfo: widgetTimeInfo,
+        formImages: imgMap
+      }
+      return defaultData;
+    }
+
     // 处理封面图片
     let imgName: string = '';
 

+ 1 - 97
entry/src/main/ets/entryformability/EntryFormAbility.ets

@@ -91,7 +91,7 @@ export default class EntryFormAbility extends FormExtensionAbility {
     });
 
     // 返回初始数据作为临时显示
-    const adaptedData = this.buildWidgetData();
+    const adaptedData = this.unifiedPlayerService.getWidgetFormData();
     console.info(`[EntryFormAbility] onAddForm returning data for ${formId}:`, JSON.stringify(adaptedData));
 
     return formBindingData.createFormBindingData(adaptedData);
@@ -173,102 +173,6 @@ export default class EntryFormAbility extends FormExtensionAbility {
     }
   }
 
-  private buildWidgetData(): FormWidgetData {
-    // 构建与UnifiedPlayerService一致的数据结构
-    try {
-      const currentSong = this.unifiedPlayerService.getCurrentSong();
-      const currentState = this.unifiedPlayerService.getCurrentState();
-      
-      if (!currentSong) {
-        const defaultData: FormWidgetData = {
-          id: '',
-          name: '未知歌曲',
-          artist: '未知艺术家',
-          album: '未知专辑',
-          pixelMapPath: '',
-          duration: 0,
-          filePath: '',
-          imgName: '',
-          imageColorHex: '2A2A2A',
-          isPlaying: false,
-          isPaused: true,
-          isLoading: false,
-          hasNext: false,
-          hasPrevious: false
-        };
-        return defaultData;
-      }
-
-      // 返回平铺数据结构,与widget组件期望的格式一致
-      const widgetData: FormWidgetData = {
-        // VideoItem数据
-        id: currentSong.id || '',
-        name: currentSong.name || '',
-        artist: currentSong.artist || '',
-        album: currentSong.album || '',
-        pixelMapPath: currentSong.pixelMapPath || '',
-        duration: typeof currentSong.duration === 'string' ? parseInt(currentSong.duration || '0') : (currentSong.duration || 0),
-        filePath: currentSong.filePath || '',
-        imgName: '',
-        imageColorHex: '2A2A2A',
-        
-        // PlayerState数据平铺
-        isPlaying: currentState.isPlaying || false,
-        isPaused: currentState.isPaused || true,
-        isLoading: currentState.isLoading || false,
-        hasNext: currentState.hasNext || false,
-        hasPrevious: currentState.hasPrevious || false,
-        playMode: currentState.playMode || 0,
-        
-        // 播放列表信息
-        currentIndex: this.unifiedPlayerService.getCurrentIndex(),
-        totalCount: this.unifiedPlayerService.getPlaylist().length,
-        
-        // 时间信息
-        currentTimeText: this.formatTimeDisplay(Math.floor((currentState.currentPosition || 0) / 1000)),
-        totalTimeText: this.formatTimeDisplay(Math.floor((currentState.duration || 0) / 1000)),
-        progressPercentage: this.calculateProgressPercentage(currentState.currentPosition || 0, currentState.duration || 0)
-      };
-      return widgetData;
-    } catch (error) {
-      console.error(`[EntryFormAbility] Failed to build widget data: ${error}`);
-      const errorData: FormWidgetData = {
-        id: '',
-        name: 'Error',
-        artist: 'Unknown',
-        album: 'Unknown',
-        pixelMapPath: '',
-        duration: 0,
-        filePath: '',
-        imgName: '',
-        imageColorHex: '2A2A2A',
-        isPlaying: false,
-        isPaused: true,
-        isLoading: false,
-        hasNext: false,
-        hasPrevious: false
-      };
-      return errorData;
-    }
-  }
-
-  /**
-   * 格式化时间显示
-   */
-  private formatTimeDisplay(seconds: number): string {
-    const mins = Math.floor(seconds / 60);
-    const secs = Math.floor(seconds % 60);
-    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
-  }
-
-  /**
-   * 计算播放进度百分比
-   */
-  private calculateProgressPercentage(current: number, total: number): number {
-    if (total <= 0) return 0;
-    return Math.min(100, Math.max(0, (current / total) * 100));
-  }
-
 
   /**
    * 保存 Form ID 到持久化存储