chendeben пре 1 година
родитељ
комит
301f26374d

+ 69 - 18
entry/src/main/ets/common/service/UnifiedPlayerService.ets

@@ -874,15 +874,22 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
       await this.playNewSongDirectly(newSong);
 
       // 更新播放列表状态
-      this.updatePlaylistStateInModel();
-
-      // 强制更新UI(如卡片)
-      if (newSong) {
-        await this.updateWidgetsForSongChange(newSong, true);
-      }
+      await this.updatePlaylistStateInModel();
 
-      // 同步更新所有桌面卡片状态
-      await this.updateAllForms();
+      // 播放新歌曲后,等待一段时间确保播放器状态稳定,然后更新卡片
+      setTimeout(async () => {
+        try {
+          // 确保播放列表状态是最新的
+          this.updatePlaylistStateInModelSync();
+          
+          // 强制更新所有桌面卡片状态
+          await this.updateAllForms(true);
+          
+          LogUtils.getInstance().LOGI('UnifiedPlayerService: Widget state updated after track change');
+        } catch (error) {
+          LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to update widgets after track change: ${error}`);
+        }
+      }, 200); // 延迟200ms确保播放器状态稳定
 
     } catch (error) {
       await this.handlePlaybackError(error as Error, PlayerErrorType.PLAYBACK_ERROR);
@@ -918,7 +925,7 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
       await this.startPlayOrResumePlay();
 
       // 更新状态模型中的播放列表状态
-      this.updatePlaylistStateInModel();
+      await this.updatePlaylistStateInModel();
 
       // 通知歌曲变化
       const currentSong = this.playlistModel.getCurrentSong();
@@ -1357,7 +1364,7 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
     this.stateModel.updateCurrentIndex(currentIndex);
 
     // 更新状态模型中的播放列表状态
-    this.updatePlaylistStateInModel();
+    this.updatePlaylistStateInModelSync();
 
     // 更新当前歌曲
     const currentSong = this.playlistModel.getCurrentSong();
@@ -1381,7 +1388,7 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
     this.playlistModel.addSong(song, index);
 
     // 更新状态模型中的播放列表状态
-    this.updatePlaylistStateInModel();
+    this.updatePlaylistStateInModelSync();
 
     // 同步到持久化存储
     this.syncPlaylistToStorage();
@@ -1398,7 +1405,7 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
       this.stateModel.updateCurrentIndex(this.playlistModel.getCurrentIndex());
 
       // 更新状态模型中的播放列表状态
-      this.updatePlaylistStateInModel();
+      this.updatePlaylistStateInModelSync();
 
       // 更新当前歌曲
       const currentSong = this.playlistModel.getCurrentSong();
@@ -1986,6 +1993,9 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
 
       // 设置一个临时的数据恢复完成标识,允许快速响应
       this.isDataRestored = true;
+      
+      // 立即更新播放列表状态,确保上一首/下一首状态正确
+      this.updatePlaylistStateInModelSync();
     } catch (error) {
       console.log(`Heanup2 UnifiedPlayerService: 快速恢复内存数据失败: ${error}`);
     }
@@ -2018,6 +2028,9 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
         }
 
         LogUtils.getInstance().LOGI(`UnifiedPlayerService: Restored playlist with ${playlistData.songs.length} songs`);
+        
+        // 立即更新播放列表状态,确保上一首/下一首状态正确
+        this.updatePlaylistStateInModelSync();
       } else {
         console.log("Heanup2 UnifiedPlayerService: 没有找到保存的播放列表或播放列表为空");
       }
@@ -2049,6 +2062,10 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
 
       // 设置数据恢复完成标识
       this.isDataRestored = true;
+      
+      // 立即更新播放列表状态,确保上一首/下一首状态正确
+      this.updatePlaylistStateInModelSync();
+      
       LogUtils.getInstance().LOGI('UnifiedPlayerService: Data restoration completed');
     } catch (error) {
       console.log(`Heanup2 UnifiedPlayerService: 恢复持久化状态时出错: ${error}`);
@@ -2282,7 +2299,10 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
    */
   async broadcastCurrentState(): Promise<void> {
     try {
-      this.updateAllForms();
+      // 确保播放列表状态是最新的
+      this.updatePlaylistStateInModelSync();
+      
+      await this.updateAllForms(true); // 强制更新
       LogUtils.getInstance().LOGI('UnifiedPlayerService: Current state broadcasted manually');
     } catch (error) {
       LogUtils.getInstance().LOGI(`UnifiedPlayerService broadcastCurrentState error: ${error}`);
@@ -2390,6 +2410,26 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
     }
   }
 
+  /**
+   * 更新状态模型中的播放列表状态(同步版本)
+   */
+  private updatePlaylistStateInModelSync(): void {
+    try {
+      const currentIndex = this.playlistModel.getCurrentIndex();
+      const totalCount = this.playlistModel.getTotalCount();
+      const playMode = this.stateModel.getState().playMode;
+
+      const hasNext = this.playlistModel.hasNext(playMode);
+      const hasPrevious = this.playlistModel.hasPreviousSync(playMode);
+
+      this.stateModel.updatePlaylistState(hasNext, hasPrevious, totalCount);
+
+      LogUtils.getInstance().LOGI(`UnifiedPlayerService: Playlist state updated sync - hasNext=${hasNext}, hasPrevious=${hasPrevious}, totalCount=${totalCount}, playMode=${playMode}`);
+    } catch (error) {
+      LogUtils.getInstance().LOGI(`UnifiedPlayerService updatePlaylistStateInModelSync error: ${error}`);
+    }
+  }
+
   // ==================== PlayerStateCallback 实现 ====================
 
   onPrepared(): void {
@@ -2408,10 +2448,18 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
 
       // 强制同步状态模型
       this.stateModel.updatePlayingState(isActuallyPlaying);
+      
+      // 确保播放列表状态是最新的
+      this.updatePlaylistStateInModelSync();
+      
+      // 延迟更新卡片,确保状态已同步
+      setTimeout(() => {
+        this.updateWidgetsForStateChange();
+      }, 50);
 
     }, 100);
 
-    // 播放器准备完成时更新卡片(移除加载状态)
+    // 播放器准备完成时立即更新卡片(移除加载状态)
     this.updateWidgetsForStateChange();
   }
 
@@ -2629,12 +2677,12 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
    * 更新所有桌面卡片状态
    * 将VideoItem和PlayerState数据传入桌面卡片,控制卡片的显示
    */
-  async updateAllForms() {
+  async updateAllForms(forceUpdate: boolean = false) {
     try {
       const now = Date.now();
       
-      // 防重复调用:如果正在更新或距离上次更新时间太近,则跳过
-      if (this.isUpdatingForms || (now - this.lastUpdateTime) < this.UPDATE_THROTTLE_MS) {
+      // 防重复调用:如果正在更新或距离上次更新时间太近,则跳过(除非强制更新)
+      if (!forceUpdate && (this.isUpdatingForms || (now - this.lastUpdateTime) < this.UPDATE_THROTTLE_MS)) {
         LogUtils.getInstance().LOGI(`UnifiedPlayerService updateAllForms: Skipping duplicate call (last update: ${now - this.lastUpdateTime}ms ago)`);
         return;
       }
@@ -2642,6 +2690,9 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
       this.isUpdatingForms = true;
       this.lastUpdateTime = now;
       
+      // 确保播放列表状态是最新的
+      this.updatePlaylistStateInModelSync();
+      
       const formData: VideoItem | null = this.getCurrentSong(); // VideoItem
       const songState: PlayerState = this.getCurrentState(); // PlayerState
       
@@ -2806,7 +2857,7 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
    */
   public async updateWidgetsForStateChange(): Promise<void> {
     try {
-      this.updateAllForms();
+      await this.updateAllForms(true); // 强制更新,因为状态确实发生了变化
       LogUtils.getInstance().LOGI(`UnifiedPlayerService: Widgets updated for state change`);
     } catch (error) {
       LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to update widgets for state change: ${error}`);

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

@@ -355,15 +355,7 @@ export default class EntryAbility extends UIAbility {
     }
 
     onForeground() {
-        // Ability has brought to foreground
-        hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onForeground start');
 
-        // 异步处理前台逻辑,避免阻塞生命周期
-        setTimeout(() => {
-            this.handleForegroundAsync();
-        }, 10);
-
-        hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onForeground end');
     }
 
     onBackground() {
@@ -653,7 +645,6 @@ export default class EntryAbility extends UIAbility {
 
             // 操作完成后,广播最新状态给主应用UI和桌面卡片
             setTimeout(() => {
-                this.broadcastCurrentPlayerState();
                 hilog.info(0x0000, 'Heanup2', '📡 桌面卡片操作后广播状态更新');
 
                 // 同时触发UnifiedPlayerService的状态广播,确保所有监听器都能收到更新
@@ -786,37 +777,12 @@ export default class EntryAbility extends UIAbility {
                     hilog.info(0x0000, 'Heanup2', '🔄 冷启动检测到数据未恢复,开始预恢复');
                     await unifiedService.forceDataRestoration();
                 }
-
-                // 延迟广播当前状态,确保卡片能接收到初始状态
-                setTimeout(() => {
-                    this.broadcastCurrentPlayerState();
-                }, 500); // 缩短延迟,让卡片更快收到状态
             } catch (error) {
                 hilog.error(0x0000, 'Heanup2', `❌ UnifiedPlayerService 异步初始化失败: ${error}`);
             }
         }, 50); // 缩短延迟,让初始化更快开始
     }
 
-    /**
-     * 异步处理前台逻辑
-     */
-    private handleForegroundAsync(): void {
-        try {
-            hilog.info(0x0000, 'Heanup2', '🔄 处理前台逻辑');
-
-            // 确保播放器服务可用
-            const playerService = UnifiedPlayerService.getInstance();
-            if (playerService) {
-                // 广播当前状态给卡片
-                this.broadcastCurrentPlayerState();
-            }
-
-            hilog.info(0x0000, 'Heanup2', '✅ 前台逻辑处理完成');
-        } catch (error) {
-            hilog.error(0x0000, 'Heanup2', `❌ 前台逻辑处理失败: ${error}`);
-        }
-    }
-
     /**
      * 异步处理后台逻辑
      */
@@ -847,67 +813,6 @@ export default class EntryAbility extends UIAbility {
         }, 200);
     }
 
-    /**
-     * 广播当前播放器状态给卡片
-     */
-    private broadcastCurrentPlayerState(): void {
-        try {
-            const unifiedService = UnifiedPlayerService.getInstance();
-            const currentState = unifiedService.getCurrentState();
-            const currentSong = unifiedService.getCurrentSong();
-            const playlist = unifiedService.getPlaylist();
-            const currentIndex = unifiedService.getCurrentIndex();
-
-            if (currentSong) {
-                // 构建播放器状态广播数据
-                const broadcastData: BroadcastData = {
-                    playState: {
-                        isPlaying: currentState.isPlaying || false,
-                        isPaused: currentState.isPaused || true,
-                        isLoading: currentState.isLoading || false
-                    } as PlayStateBroadcast,
-                    currentSong: {
-                        id: currentSong.id || '',
-                        title: currentSong.name || '暂无播放',
-                        artist: currentSong.artist || '未知艺术家',
-                        album: currentSong.album || '未知专辑',
-                        coverImagePath: currentSong.pixelMapPath || '',
-                        duration: currentSong.duration ? Number(currentSong.duration) : 0
-                    } as SongBroadcast,
-                    progress: {
-                        currentPosition: currentState.currentPosition || 0,
-                        duration: currentState.duration || 0,
-                        percentage: this.calculatePercentage(currentState.currentPosition || 0, currentState.duration || 0),
-                        currentTimeText: this.formatTime(Math.floor((currentState.currentPosition || 0) / 1000)),
-                        totalTimeText: this.formatTime(Math.floor((currentState.duration || 0) / 1000))
-                    } as ProgressBroadcast,
-                    playlist: {
-                        hasNext: currentState.hasNext || false,
-                        hasPrevious: currentState.hasPrevious || false,
-                        currentIndex: currentIndex,
-                        totalCount: playlist.length
-                    } as PlaylistBroadcast
-                };
-
-                // 发送状态变化事件
-                const publishInfo: PublishInfo = {
-                    data: JSON.stringify(broadcastData)
-                };
-
-                // 使用emitter发送事件
-                const eventData: EventDataWrapper = {
-                    data: broadcastData
-                };
-                emitter.emit({ eventId: 1001 }, eventData); // 使用特定的事件ID
-
-                hilog.info(0x0000, 'Heanup2', `📡 Broadcasted current player state: ${currentSong.name}, isPlaying=${currentState.isPlaying}`);
-            } else {
-                hilog.info(0x0000, 'Heanup2', '📡 No current song to broadcast');
-            }
-        } catch (error) {
-            hilog.error(0x0000, 'Heanup2', `❌ Failed to broadcast current player state: ${error}`);
-        }
-    }
 
     /**
      * 计算播放进度百分比