Parcourir la source

修复小问题

chendeben il y a 1 an
Parent
commit
bb7b2b21df

+ 86 - 6
entry/src/main/ets/common/service/UnifiedPlayerService.ets

@@ -363,6 +363,7 @@ export interface IPlayerService {
    * @returns 收藏列表
    * @returns 收藏列表
    */
    */
   getFav(): Array<VideoItem>;
   getFav(): Array<VideoItem>;
+  syncPlaylistToService(songList: VideoItem[], currentIndex: number, playType: PlayMode): void
 }
 }
 
 
 /**
 /**
@@ -1565,6 +1566,36 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
     return removedSong;
     return removedSong;
   }
   }
 
 
+  /**
+   * 同步播放列表到服务
+   * 从LocalMusic迁移的方法,用于统一调用
+   */
+  syncPlaylistToService(songList: VideoItem[], currentIndex: number, playType: PlayMode): void {
+    try {
+      if (songList && songList.length > 0) {
+        // 记录调用栈信息以便调试
+        const stack = new Error().stack || 'No stack available';
+        const caller = stack.split('\n')[2] || 'Unknown caller';
+
+        this.setPlaylist(songList, currentIndex);
+
+        // 同步播放模式到UnifiedPlayerService
+        this.setPlayMode(playType);
+
+        LogUtils.getInstance().LOGI(`UnifiedPlayerService: Playlist and play mode synced - ${songList.length} songs, mode: ${playType}, caller: ${caller.trim()}`);
+
+        // 如果同步的是小播放列表,记录更多信息
+        if (songList.length <= 20) {
+          LogUtils.getInstance().LOGI(`UnifiedPlayerService: Small playlist sync detected, first few songs: ${songList.slice(0, 5).map(s => s.name).join(', ')}`);
+        }
+      } else {
+        LogUtils.getInstance().LOGI('UnifiedPlayerService: syncPlaylistToService - No songs to sync');
+      }
+    } catch (error) {
+      LogUtils.getInstance().LOGI(`UnifiedPlayerService syncPlaylistToService error: ${error}`);
+    }
+  }
+
   // 事件监听
   // 事件监听
   addStateListener(listener: PlayerStateListener): void {
   addStateListener(listener: PlayerStateListener): void {
     this.stateModel.addStateListener(listener);
     this.stateModel.addStateListener(listener);
@@ -1589,9 +1620,24 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
         this.avMetadataUpdateTimer = -1;
         this.avMetadataUpdateTimer = -1;
       }
       }
 
 
-      // 保存当前状态
-      this.saveCurrentState();
+      // 重要修复:确保在应用销毁时将播放状态设置为停止
+      try {
+        // 强制设置为停止状态,防止卡片显示错误的播放状态
+        this.stateModel.updatePlayingState(false);
+        this.stateModel.updateLoadingState(false);
+        
+        // 确保播放器也停止
+        if (this.playerManager) {
+          this.playerManager.release() ;
+        }
+        
+        LogUtils.getInstance().LOGI('UnifiedPlayerService: Forced stop state before release');
+      } catch (error) {
+        LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to force stop state: ${error}`);
+      }
 
 
+      // 保存当前状态(现在应该是停止状态)
+      this.saveCurrentState();
 
 
       if (this.avSessionController) {
       if (this.avSessionController) {
         this.avSessionController.unregisterSessionListener();
         this.avSessionController.unregisterSessionListener();
@@ -1603,6 +1649,7 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
       this.playlistSync.release();
       this.playlistSync.release();
 
 
       this.playerManager.release();
       this.playerManager.release();
+
       this.playlistModel.clear();
       this.playlistModel.clear();
       this.isInitialized = false;
       this.isInitialized = false;
 
 
@@ -1997,6 +2044,9 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
     LogUtils.getInstance().LOGI('UnifiedPlayerService: Progress timer started');
     LogUtils.getInstance().LOGI('UnifiedPlayerService: Progress timer started');
   }
   }
 
 
+  /**
+   * 停止进度定时器
+   */
   private stopProgressTimer(): void {
   private stopProgressTimer(): void {
     if (this.progressTimer !== -1) {
     if (this.progressTimer !== -1) {
       clearInterval(this.progressTimer);
       clearInterval(this.progressTimer);
@@ -2228,18 +2278,48 @@ export class UnifiedPlayerService implements IPlayerService, PlaylistSyncListene
    */
    */
   private saveCurrentState(): void {
   private saveCurrentState(): void {
     try {
     try {
-      // 保存播放状态
+      // 获取当前状态
       const currentState = this.stateModel.getState();
       const currentState = this.stateModel.getState();
-      this.dataPersistence.savePlayerState(currentState)
+      
+      // 验证播放器实际状态,确保状态模型与实际播放器状态一致
+      try {
+        const ijkPlayer = this.playerManager.getIjkPlayer();
+        const actualPlaying = ijkPlayer ? ijkPlayer.isPlaying() : false;
+        
+        // 如果状态不一致,以实际播放器状态为准
+        if (currentState.isPlaying !== actualPlaying) {
+          LogUtils.getInstance().LOGI(`UnifiedPlayerService: State mismatch detected during save - StateModel: ${currentState.isPlaying}, Actual: ${actualPlaying}`);
+          this.stateModel.updatePlayingState(actualPlaying);
+          // 重新获取修正后的状态
+          const correctedState = this.stateModel.getState();
+          this.dataPersistence.savePlayerState(correctedState);
+        } else {
+          this.dataPersistence.savePlayerState(currentState);
+        }
+      } catch (playerError) {
+        // 如果获取播放器状态失败,默认保存为停止状态
+        LogUtils.getInstance().LOGI(`UnifiedPlayerService: Failed to get actual player state, saving as stopped: ${playerError}`);
+        this.stateModel.updatePlayingState(false);
+        const stoppedState = this.stateModel.getState();
+        this.dataPersistence.savePlayerState(stoppedState);
+      }
 
 
-      // 保存播放进度
       this.savePlaybackPosition();
       this.savePlaybackPosition();
-
+      this.syncPlaylistToStorage();
+      
+      LogUtils.getInstance().LOGI(`UnifiedPlayerService: Current state saved successfully`);
     } catch (error) {
     } catch (error) {
       LogUtils.getInstance().LOGI(`UnifiedPlayerService saveCurrentState error: ${error}`);
       LogUtils.getInstance().LOGI(`UnifiedPlayerService saveCurrentState error: ${error}`);
     }
     }
   }
   }
 
 
+  /**
+   * 外部调用保存当前状态的方法(供EntryAbility使用)
+   */
+  public saveCurrentStateExternal(): void {
+    this.saveCurrentState();
+  }
+
   /**
   /**
    * 同步播放列表到存储
    * 同步播放列表到存储
    */
    */

+ 12 - 17
entry/src/main/ets/entryability/EntryAbility.ets

@@ -805,6 +805,18 @@ export default class EntryAbility extends UIAbility {
         try {
         try {
             hilog.info(0x0000, 'Heanup2', '🔄 处理后台逻辑');
             hilog.info(0x0000, 'Heanup2', '🔄 处理后台逻辑');
 
 
+            // 关键修复:应用进入后台时保存播放器状态
+            try {
+                const unifiedPlayerService = UnifiedPlayerService.getInstance();
+                if (unifiedPlayerService && unifiedPlayerService.isAllServicesReady()) {
+                    // 保存当前状态,确保即使应用被强制杀死也能保存正确状态
+                    unifiedPlayerService.saveCurrentStateExternal();
+                    hilog.info(0x0000, 'Heanup2', '✅ 播放器状态已保存(后台)');
+                }
+            } catch (error) {
+                hilog.error(0x0000, 'Heanup2', `❌ 保存播放器状态失败: ${error}`);
+            }
+
             // 后台时可以执行一些清理或保存操作
             // 后台时可以执行一些清理或保存操作
             // 但要确保不会阻塞生命周期
             // 但要确保不会阻塞生命周期
 
 
@@ -829,23 +841,6 @@ export default class EntryAbility extends UIAbility {
     }
     }
 
 
 
 
-    /**
-     * 计算播放进度百分比
-     */
-    private calculatePercentage(current: number, total: number): number {
-        if (total <= 0) return 0;
-        return Math.min(100, Math.max(0, (current / total) * 100));
-    }
-
-    /**
-     * 格式化时间显示
-     */
-    private formatTime(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')}`;
-    }
-
     /**
     /**
      * 清理所有Form ID
      * 清理所有Form ID
      * 应用销毁时调用,确保清理所有持久化的Form ID
      * 应用销毁时调用,确保清理所有持久化的Form ID

+ 8 - 24
entry/src/main/ets/view/LocalMusic.ets

@@ -1396,7 +1396,7 @@ export struct LocalMusic {
           this.sonDataSource.pushArrayData(this.songList);
           this.sonDataSource.pushArrayData(this.songList);
 
 
           // 同步到统一播放器服务进行持久化
           // 同步到统一播放器服务进行持久化
-          this.syncPlaylistToService();
+          this.unifiedPlayerService.syncPlaylistToService(this.songList, this.curIndex, this.playType);
 
 
         }
         }
       }
       }
@@ -4982,7 +4982,7 @@ export struct LocalMusic {
         this.justSwitched = true; // 标记歌曲刚刚切换
         this.justSwitched = true; // 标记歌曲刚刚切换
 
 
         // 同步播放列表到UnifiedPlayerService
         // 同步播放列表到UnifiedPlayerService
-        this.syncPlaylistToService();
+        this.unifiedPlayerService.syncPlaylistToService(this.songList, this.curIndex, this.playType);
         this.startPlayOrResumePlay()
         this.startPlayOrResumePlay()
         break;
         break;
 
 
@@ -10493,29 +10493,13 @@ export struct LocalMusic {
   }
   }
 
 
   // 同步播放列表到UnifiedPlayerService
   // 同步播放列表到UnifiedPlayerService
+  // @deprecated 请使用 unifiedPlayerService.syncPlaylistToService() 代替
   private syncPlaylistToService() {
   private syncPlaylistToService() {
     try {
     try {
-      if (ArrayUtil.isNotEmpty(this.songList)) {
-        // 记录调用栈信息以便调试
-        const stack = new Error().stack || 'No stack available';
-        const caller = stack.split('\n')[2] || 'Unknown caller';
-
-        this.unifiedPlayerService.setPlaylist(this.songList, this.curIndex);
-
-        // 同步播放模式到UnifiedPlayerService
-        this.unifiedPlayerService.setPlayMode(this.playType);
-
-        LogUtils.getInstance().LOGI(`LocalMusic: Playlist and play mode synced to UnifiedPlayerService - ${this.songList.length} songs, mode: ${this.playType}, caller: ${caller.trim()}`);
-
-        // 如果同步的是小播放列表,记录更多信息
-        if (this.songList.length <= 20) {
-          LogUtils.getInstance().LOGI(`LocalMusic: Small playlist sync detected, current path: ${this.currentPath}, first few songs: ${this.songList.slice(0, 5).map(s => s.name).join(', ')}`);
-        }
-      } else {
-        LogUtils.getInstance().LOGI('LocalMusic: syncPlaylistToService - No songs to sync');
-      }
+      // 直接调用统一服务的方法
+      this.unifiedPlayerService.syncPlaylistToService(this.songList, this.curIndex, this.playType);
     } catch (error) {
     } catch (error) {
-      LogUtils.getInstance().LOGI(`LocalMusic syncPlaylistToService error: ${error}`);
+      LogUtils.getInstance().LOGI(`LocalMusic syncPlaylistToService (deprecated) error: ${error}`);
     }
     }
   }
   }
 
 
@@ -11849,7 +11833,7 @@ export struct LocalMusic {
       this.fallbackPlayNext();
       this.fallbackPlayNext();
     }
     }
     // 同步播放列表到UnifiedPlayerService
     // 同步播放列表到UnifiedPlayerService
-    this.syncPlaylistToService();
+    this.unifiedPlayerService.syncPlaylistToService(this.songList, this.curIndex, this.playType);
   }
   }
 
 
   // 回退到原有的playNext逻辑
   // 回退到原有的playNext逻辑
@@ -12033,7 +12017,7 @@ export struct LocalMusic {
       this.fallbackPlayPrevious();
       this.fallbackPlayPrevious();
     }
     }
     // 同步播放列表到UnifiedPlayerService
     // 同步播放列表到UnifiedPlayerService
-    this.syncPlaylistToService();
+    this.unifiedPlayerService.syncPlaylistToService(this.songList, this.curIndex, this.playType);
   }
   }
 
 
   // 回退到原有的playPrevious逻辑
   // 回退到原有的playPrevious逻辑