Просмотр исходного кода

修复播放恢复时进度条问题

chendeben 1 год назад
Родитель
Сommit
5f6a54bb5c

+ 82 - 12
entry/src/main/ets/common/service/PlayerManager.ets

@@ -38,10 +38,13 @@ export interface IPlayerManager {
   startPlayOrResumePlay(): Promise<void>;
   pausePlayback(): void;
   stopPlayback(): void;
-  seekToPosition(position: string): void;
+  seekToPosition(position: string): Promise<void>;
   setPlaybackSpeed(speed: string): void;
   setVolume(leftVolume: string, rightVolume: string): void;
   
+  // 状态查询
+  isPausedState(): boolean;
+  
   // 清理资源
   release(): void;
 }
@@ -56,6 +59,7 @@ export class PlayerManager implements IPlayerManager {
   private mContext: common.UIAbilityContext | null = null;
   private audioInterruptCallback: ((event: InterruptEvent) => void) | null = null;
   private stateCallback: PlayerStateCallback | null = null;
+  private isPaused: boolean = false; // 跟踪暂停状态
   
   private constructor() {
     this.mIjkMediaPlayer = IjkMediaPlayer.getInstance();
@@ -153,10 +157,18 @@ export class PlayerManager implements IPlayerManager {
       onPrepared: () => {
         LogUtils.getInstance().LOGI('PlayerManager: Player prepared, starting playback');
         try {
-          this.mIjkMediaPlayer.start();
-          LogUtils.getInstance().LOGI('PlayerManager: Playback started after prepared');
+          // 只有在非暂停状态下才自动开始播放
+          // 如果当前是暂停状态,仅通知准备完成,不自动开始播放
+          if (!this.isPaused) {
+            this.mIjkMediaPlayer.start();
+            LogUtils.getInstance().LOGI('PlayerManager: Playback started after prepared');
+            this.stateCallback?.onPlaybackStarted();
+          } else {
+            LogUtils.getInstance().LOGI('PlayerManager: Player prepared but in paused state, not auto-starting');
+          }
+          
+          // 总是通知准备完成
           this.stateCallback?.onPrepared();
-          this.stateCallback?.onPlaybackStarted();
         } catch (error) {
           LogUtils.getInstance().LOGI(`PlayerManager: Failed to start after prepared: ${error}`);
           this.stateCallback?.onPlaybackError(-1, -1);
@@ -206,10 +218,32 @@ export class PlayerManager implements IPlayerManager {
         return;
       }
       
+      const currentPosition = this.mIjkMediaPlayer.getCurrentPosition();
+      const duration = this.mIjkMediaPlayer.getDuration();
+      const wasPaused = this.isPaused;
+      
+      LogUtils.getInstance().LOGI(`PlayerManager: Starting/resuming playback (isPaused: ${wasPaused}, position: ${currentPosition}ms, duration: ${duration}ms)`);
+      
       // 对于暂停后的恢复播放,直接调用start()
       // 对于新的播放,需要先调用prepareAsync(),在onPrepared回调中自动开始播放
       this.mIjkMediaPlayer.start();
-      LogUtils.getInstance().LOGI('PlayerManager: Playback started/resumed');
+      
+      if (wasPaused) {
+        // 从暂停状态恢复,清除暂停标记
+        this.isPaused = false;
+        LogUtils.getInstance().LOGI(`PlayerManager: Resumed from paused state at position ${currentPosition}ms`);
+      } else {
+        LogUtils.getInstance().LOGI('PlayerManager: Started new playback');
+      }
+      
+      // 验证播放是否真正开始
+      setTimeout(() => {
+        const isNowPlaying = this.mIjkMediaPlayer.isPlaying();
+        const newPosition = this.mIjkMediaPlayer.getCurrentPosition();
+        LogUtils.getInstance().LOGI(`PlayerManager: Playback verification - isPlaying: ${isNowPlaying}, position: ${newPosition}ms`);
+      }, 100);
+      
+      LogUtils.getInstance().LOGI('PlayerManager: Playback started/resumed successfully');
     } catch (error) {
       LogUtils.getInstance().LOGI(`PlayerManager startPlayOrResumePlay error: ${error}`);
       throw new Error(`Failed to start playback: ${error}`);
@@ -218,10 +252,13 @@ export class PlayerManager implements IPlayerManager {
 
   pausePlayback(): void {
     try {
-      if (this.mIjkMediaPlayer.isPlaying()) {
-        this.mIjkMediaPlayer.pause();
-        LogUtils.getInstance().LOGI('PlayerManager: Playback paused');
-      }
+      // 先设置暂停标志,确保状态优先级
+      this.isPaused = true;
+      
+      // 无论播放器报告的状态如何,都尝试暂停
+      this.mIjkMediaPlayer.pause();
+      
+      LogUtils.getInstance().LOGI('PlayerManager: Playback paused, isPaused flag set to true');
     } catch (error) {
       LogUtils.getInstance().LOGI(`PlayerManager pausePlayback error: ${error}`);
     }
@@ -230,18 +267,21 @@ export class PlayerManager implements IPlayerManager {
   stopPlayback(): void {
     try {
       this.mIjkMediaPlayer.stop();
-      this.mIjkMediaPlayer.release();
+      this.isPaused = false; // 清除暂停状态
+      // 注意:不要在这里调用release(),因为这会释放播放器资源
+      // release()应该只在真正需要释放资源时调用(如应用退出)
       LogUtils.getInstance().LOGI('PlayerManager: Playback stopped');
     } catch (error) {
       LogUtils.getInstance().LOGI(`PlayerManager stopPlayback error: ${error}`);
     }
   } 
- seekToPosition(position: string): void {
+ async seekToPosition(position: string): Promise<void> {
     try {
       this.mIjkMediaPlayer.seekTo(position);
       LogUtils.getInstance().LOGI(`PlayerManager: Seeked to position ${position}`);
     } catch (error) {
       LogUtils.getInstance().LOGI(`PlayerManager seekToPosition error: ${error}`);
+      throw new Error(`Failed to seek to position: ${error}`);
     }
   }
 
@@ -263,6 +303,31 @@ export class PlayerManager implements IPlayerManager {
     }
   }
 
+  isPausedState(): boolean {
+    try {
+      // 多重检查确保暂停状态的准确性
+      const internalPausedFlag = this.isPaused;
+      const playerIsPlaying = this.mIjkMediaPlayer.isPlaying();
+      const hasDuration = this.mIjkMediaPlayer.getDuration() > 0;
+      
+      // 如果内部标记为暂停,直接返回true(优先级最高)
+      if (internalPausedFlag) {
+        LogUtils.getInstance().LOGI(`PlayerManager isPausedState: internal=${internalPausedFlag}, isPlaying=${playerIsPlaying}, hasDuration=${hasDuration}, result=true (internal priority)`);
+        return true;
+      }
+      
+      // 如果播放器有时长但没有播放,也认为是暂停状态(但要排除加载中的情况)
+      const playerNotPlayingButReady = !playerIsPlaying && hasDuration;
+      
+      LogUtils.getInstance().LOGI(`PlayerManager isPausedState: internal=${internalPausedFlag}, isPlaying=${playerIsPlaying}, hasDuration=${hasDuration}, result=${playerNotPlayingButReady}`);
+      
+      return playerNotPlayingButReady;
+    } catch (error) {
+      LogUtils.getInstance().LOGI(`PlayerManager isPausedState error: ${error}`);
+      return this.isPaused; // 发生错误时返回内部标记
+    }
+  }
+
   release(): void {
     try {
       // 移除音频中断监听
@@ -273,7 +338,12 @@ export class PlayerManager implements IPlayerManager {
       
       // 停止播放并释放资源
       this.mIjkMediaPlayer.setScreenOnWhilePlaying(false);
-      this.stopPlayback();
+      
+      // 先停止播放
+      this.mIjkMediaPlayer.stop();
+      
+      // 然后释放播放器资源
+      this.mIjkMediaPlayer.release();
       
       LogUtils.getInstance().LOGI('PlayerManager: Resources released');
     } catch (error) {

+ 6 - 1
entry/src/main/ets/common/service/PlayerStateModel.ets

@@ -126,12 +126,17 @@ export class PlayerStateModel {
    * 更新播放状态
    */
   updatePlayingState(isPlaying: boolean): void {
+    const wasPlaying = this.state.isPlaying;
+    const wasPaused = this.state.isPaused;
+    
     if (this.state.isPlaying !== isPlaying) {
       this.state.isPlaying = isPlaying;
       this.state.isPaused = !isPlaying;
       this.state.isLoading = false;
+      
+      LogUtils.getInstance().LOGI(`PlayerStateModel: Playing state updated from ${wasPlaying} to ${isPlaying}, paused from ${wasPaused} to ${!isPlaying}`);
+      
       this.notifyStateChanged();
-      LogUtils.getInstance().LOGI(`PlayerStateModel: Playing state updated to ${isPlaying}`);
     }
   }
 

+ 220 - 82
entry/src/main/ets/common/service/UnifiedPlayerService.ets

@@ -112,26 +112,12 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
     }
 
     try {
-      console.log("Heanup2 UnifiedPlayerService: 开始初始化服务");
+      console.log("Heanup2 UnifiedPlayerService: 开始快速初始化服务");
       this.context = context;
       
-      // 初始化各个服务
-      await this.playerManager.initialize(context);
-      
-      // 设置播放器状态回调
+      // 快速初始化核心组件
       this.playerManager.setStateCallback(this);
-      LogUtils.getInstance().LOGI('UnifiedPlayerService: PlayerManager state callback set');
-      
-      await this.dataPersistence.initialize(context);
-      await this.playlistSync.initialize(context);
-      await this.stateSync.initialize(context);
-      
-      // 初始化卡片更新服务
       this.widgetUpdateService.setAppContext(context);
-      LogUtils.getInstance().LOGI('UnifiedPlayerService: Widget update service initialized');
-      
-      // 初始化AVSession控制器
-      this.initializeAvSession();
       
       // 设置同步监听器
       this.playlistSync.addSyncListener(this);
@@ -181,19 +167,54 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
       const stateListener = new StateListenerImpl(this.stateSync, this.widgetUpdateService, this);
       this.stateModel.addStateListener(stateListener);
       
-      // 恢复保存的状态
-      await this.restorePersistedState();
-      
       this.setupProgressTimer();
       this.isInitialized = true;
       
-      LogUtils.getInstance().LOGI('UnifiedPlayerService: Initialized successfully');
+      // 异步初始化耗时组件,避免阻塞
+      this.initializeHeavyComponentsAsync(context);
+      
+      LogUtils.getInstance().LOGI('UnifiedPlayerService: Core initialization completed');
     } catch (error) {
       LogUtils.getInstance().LOGI(`UnifiedPlayerService initialization error: ${error}`);
-      throw new Error;
+      throw new Error(`初始化失败: ${error}`);
     }
   }
 
+  /**
+   * 异步初始化耗时组件
+   */
+  private initializeHeavyComponentsAsync(context: common.UIAbilityContext): void {
+    setTimeout(async () => {
+      try {
+        console.log("Heanup2 UnifiedPlayerService: 开始异步初始化耗时组件");
+        
+        // 并行初始化各个服务以提高效率
+        const initPromises = [
+          this.playerManager.initialize(context),
+          this.dataPersistence.initialize(context),
+          this.playlistSync.initialize(context),
+          this.stateSync.initialize(context)
+        ];
+        
+        await Promise.all(initPromises);
+        
+        // 初始化AVSession控制器
+        this.initializeAvSession();
+        
+        // 恢复保存的状态
+        await this.restorePersistedState();
+        
+        console.log("Heanup2 UnifiedPlayerService: 异步组件初始化完成");
+        LogUtils.getInstance().LOGI('UnifiedPlayerService: Heavy components initialized');
+      } catch (error) {
+        console.log(`Heanup2 UnifiedPlayerService: 异步组件初始化失败: ${error}`);
+        LogUtils.getInstance().LOGI(`UnifiedPlayerService heavy components init error: ${error}`);
+        // 即使失败也设置数据恢复完成,避免无限等待
+        this.isDataRestored = true;
+      }
+    }, 50); // 短延迟,让主初始化先完成
+  }
+
   // 播放控制方法
   async startPlayOrResumePlay(): Promise<void> {
     try {
@@ -244,20 +265,90 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
         return;
       }
 
-      // 如果是暂停状态,直接恢复播放
-      if (this.stateModel.getState().isPaused && !this.stateModel.getState().isLoading) {
-        await this.playerManager.startPlayOrResumePlay();
-        this.stateModel.updatePlayingState(true);
-        this.startProgressTimer();
-        
-        // 保存播放状态变化
-        this.saveCurrentState();
-        
-        // 更新卡片显示播放状态
-        await this.updateWidgetsForPlayStateChange(true);
-        
+      // 检查播放器状态,优先处理暂停恢复情况
+      const ijkPlayer = this.playerManager.getIjkPlayer();
+      const isPausedByManager = this.playerManager.isPausedState();
+      const isCurrentlyPlaying = ijkPlayer ? ijkPlayer.isPlaying() : false;
+      const currentPlayerState = this.stateModel.getState();
+      
+      console.log(`Heanup2 UnifiedPlayerService: 播放器状态检查 - isPausedByManager: ${isPausedByManager}, isCurrentlyPlaying: ${isCurrentlyPlaying}, stateIsPlaying: ${currentPlayerState.isPlaying}, isPaused: ${currentPlayerState.isPaused}`);
+      
+      // 更严格的暂停状态检查:
+      // 1. PlayerManager明确标记为暂停状态,AND
+      // 2. 播放器当前不在播放状态,AND
+      // 3. 播放器有有效的数据源(时长 > 0),AND
+      // 4. 状态模型显示为暂停状态或非播放状态
+      const shouldResumeFromPause = isPausedByManager && 
+        !isCurrentlyPlaying && 
+        ijkPlayer && 
+        ijkPlayer.getDuration() > 0 && 
+        (currentPlayerState.isPaused || !currentPlayerState.isPlaying);
+      
+      // 额外检查:如果播放器正在播放,绝对不应该进入暂停恢复逻辑
+      if (isCurrentlyPlaying) {
+        console.log("Heanup2 UnifiedPlayerService: 播放器正在播放,跳过暂停恢复检查");
+        // 直接返回,不做任何操作,避免重置播放器
+        this.stateModel.updateLoadingState(false);
+        LogUtils.getInstance().LOGI('UnifiedPlayerService: Player already playing, no action needed');
         return;
       }
+      
+      if (shouldResumeFromPause && ijkPlayer) {
+        LogUtils.getInstance().LOGI('UnifiedPlayerService: Resuming from paused state');
+        console.log("Heanup2 UnifiedPlayerService: 检测到暂停状态,准备恢复播放");
+        
+        try {
+          // 检查播放器是否已经有数据源
+          const currentPosition = ijkPlayer.getCurrentPosition();
+          const duration = ijkPlayer.getDuration();
+          console.log(`Heanup2 UnifiedPlayerService: 当前播放位置 ${currentPosition}ms, 总时长 ${duration}ms`);
+          
+          // 只要播放器有有效的时长信息,就说明已经准备好,可以直接恢复
+          if (duration > 0) {
+            console.log("Heanup2 UnifiedPlayerService: 播放器已准备,直接恢复播放");
+            
+            // 更新加载状态为false(恢复播放不需要加载)
+            this.stateModel.updateLoadingState(false);
+            
+            // 直接恢复播放,不需要重新准备
+            await this.playerManager.startPlayOrResumePlay();
+            
+            // 手动更新播放状态
+            this.stateModel.updatePlayingState(true);
+            
+            // 启动进度定时器
+            this.startProgressTimer();
+            
+            // 立即更新一次进度,确保UI显示正确的当前位置
+            setTimeout(() => {
+              this.updateProgress();
+            }, 100);
+            
+            // 保存播放状态变化
+            this.saveCurrentState();
+            
+            // 更新AVSession播放状态
+            setTimeout(() => {
+              this.updateSessionPlayState(true);
+              LogUtils.getInstance().LOGI('UnifiedPlayerService: AVSession updated for resume from pause');
+            }, 200);
+            
+            // 更新卡片显示播放状态
+            await this.updateWidgetsForPlayStateChange(true);
+            
+            LogUtils.getInstance().LOGI('UnifiedPlayerService: Successfully resumed from paused state');
+            console.log("Heanup2 UnifiedPlayerService: 暂停恢复播放成功");
+            return;
+          } else {
+            console.log("Heanup2 UnifiedPlayerService: 播放器时长为0,需要重新准备");
+          }
+        } catch (error) {
+          console.log(`Heanup2 UnifiedPlayerService: 暂停恢复失败: ${error},将重新准备播放器`);
+          LogUtils.getInstance().LOGI(`UnifiedPlayerService: Resume from pause failed: ${error}, will re-prepare player`);
+        }
+      } else {
+        console.log(`Heanup2 UnifiedPlayerService: 不满足暂停恢复条件 - shouldResumeFromPause: ${shouldResumeFromPause}, isPausedByManager: ${isPausedByManager}, isCurrentlyPlaying: ${isCurrentlyPlaying}`);
+      }
 
       // 检查文件是否存在(对于本地文件)
       if (!currentSong.filePath.startsWith('http')) {
@@ -354,21 +445,53 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
 
   async pause(): Promise<void> {
     try {
+      LogUtils.getInstance().LOGI('UnifiedPlayerService: Pausing playback');
+      console.log("Heanup2 UnifiedPlayerService: 开始暂停播放");
+      
+      const ijkPlayer = this.playerManager.getIjkPlayer();
+      if (ijkPlayer) {
+        const currentPosition = ijkPlayer.getCurrentPosition();
+        const duration = ijkPlayer.getDuration();
+        console.log(`Heanup2 UnifiedPlayerService: 暂停时的播放位置 ${currentPosition}ms, 总时长 ${duration}ms`);
+      }
+      
+      // 保存当前播放位置
       this.savePlaybackPosition();
+      
+      // 暂停播放器 - 确保先暂停播放器
       this.playerManager.pausePlayback();
+      
+      // 立即更新状态模型为暂停状态,确保状态同步
       this.stateModel.updatePlayingState(false);
+      
+      // 停止进度定时器
       this.stopProgressTimer();
       
+      // 等待一小段时间确保播放器状态稳定
+      await new Promise<void>(resolve => setTimeout(resolve, 50));
+      
       // 保存播放状态变化
       this.saveCurrentState();
       
       // 立即更新AVSession播放状态
       this.updateSessionPlayState(false);
       
-      LogUtils.getInstance().LOGI('UnifiedPlayerService: Playback paused');
+      // 更新卡片显示暂停状态
+      await this.updateWidgetsForPlayStateChange(false);
+      
+      // 验证暂停状态
+      setTimeout(() => {
+        const isManagerPaused = this.playerManager.isPausedState();
+        const stateModelState = this.stateModel.getState();
+        console.log(`Heanup2 UnifiedPlayerService: 暂停后状态验证 - Manager暂停: ${isManagerPaused}, State模型暂停: ${stateModelState.isPaused}, State模型播放: ${stateModelState.isPlaying}`);
+      }, 100);
+      
+      LogUtils.getInstance().LOGI('UnifiedPlayerService: Playback paused successfully');
+      console.log("Heanup2 UnifiedPlayerService: 暂停播放成功");
     } catch (error) {
       LogUtils.getInstance().LOGI(`UnifiedPlayerService pause error: ${error}`);
-      throw new Error;
+      console.log(`Heanup2 UnifiedPlayerService: 暂停播放出错: ${error}`);
+      throw new Error(`Failed to pause playback: ${error}`);
     }
   }
 
@@ -399,11 +522,11 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
         throw new Error('WMA format does not support seeking');
       }
 
-      this.playerManager.seekToPosition(position);
+      await this.playerManager.seekToPosition(position);
       LogUtils.getInstance().LOGI(`UnifiedPlayerService: Seeked to position ${position}`);
     } catch (error) {
       LogUtils.getInstance().LOGI(`UnifiedPlayerService seekTo error: ${error}`);
-      throw new Error;
+      throw new Error(`Failed to seek to position: ${error}`);
     }
   }
 
@@ -1013,7 +1136,9 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
       throw new Error('Player not initialized');
     }
 
-    // 重置播放器
+    console.log("Heanup2 UnifiedPlayerService: 开始重新设置播放器,这会重置所有状态");
+
+    // 重置播放器 - 这会清除所有状态包括播放位置
     ijkPlayer.reset();
     
     // 重新设置音频模式 - 重置后需要重新设置
@@ -1050,6 +1175,7 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
     ijkPlayer.setMessageListener();
     
     LogUtils.getInstance().LOGI(`UnifiedPlayerService: Player setup for song ${song.name}`);
+    console.log("Heanup2 UnifiedPlayerService: 播放器重新设置完成,准备开始新的播放");
   }  
   private setupProgressTimer(): void {
     this.progressTimer = setInterval(() => {
@@ -1058,40 +1184,50 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
   }
 
   private startProgressTimer(): void {
-    if (this.progressTimer === -1) {
-      this.setupProgressTimer();
-    }
+    // 先停止现有的定时器,避免重复启动
+    this.stopProgressTimer();
+    
+    // 启动新的定时器
+    this.setupProgressTimer();
+    LogUtils.getInstance().LOGI('UnifiedPlayerService: Progress timer started');
   }
 
   private stopProgressTimer(): void {
     if (this.progressTimer !== -1) {
       clearInterval(this.progressTimer);
       this.progressTimer = -1;
+      LogUtils.getInstance().LOGI('UnifiedPlayerService: Progress timer stopped');
     }
   }
 
   private updateProgress(): void {
     try {
       const ijkPlayer = this.playerManager.getIjkPlayer();
-      if (!ijkPlayer || !this.stateModel.getState().isPlaying) {
+      const currentState = this.stateModel.getState();
+      
+      // 只有在播放器存在且正在播放时才更新进度
+      if (!ijkPlayer || !currentState.isPlaying) {
         return;
       }
 
       const currentPosition = ijkPlayer.getCurrentPosition();
       const duration = ijkPlayer.getDuration();
       
-      this.stateModel.updateProgress(currentPosition, duration);
-      
-      // 定期更新AVSession播放状态,确保系统媒体控制界面显示正确的进度
-      // 前30秒每3秒更新一次,之后每10秒更新一次
-      const now = Date.now();
-      const timeSinceStart = now - (this.lastAvSessionUpdate || now);
-      const updateInterval = timeSinceStart < 30000 ? 3000 : 10000; // 前30秒3秒一次,之后10秒一次
-      
-      if (!this.lastAvSessionUpdate || now - this.lastAvSessionUpdate > updateInterval) {
-        this.lastAvSessionUpdate = now;
-        this.updateSessionPlayState(true);
-        LogUtils.getInstance().LOGI(`UnifiedPlayerService: AVSession progress updated - Position: ${currentPosition}ms, Duration: ${duration}ms`);
+      // 确保获取到有效的位置信息
+      if (currentPosition >= 0 && duration > 0) {
+        this.stateModel.updateProgress(currentPosition, duration);
+        
+        // 定期更新AVSession播放状态,确保系统媒体控制界面显示正确的进度
+        // 前30秒每3秒更新一次,之后每10秒更新一次
+        const now = Date.now();
+        const timeSinceStart = now - (this.lastAvSessionUpdate || now);
+        const updateInterval = timeSinceStart < 30000 ? 3000 : 10000; // 前30秒3秒一次,之后10秒一次
+        
+        if (!this.lastAvSessionUpdate || now - this.lastAvSessionUpdate > updateInterval) {
+          this.lastAvSessionUpdate = now;
+          this.updateSessionPlayState(true);
+          LogUtils.getInstance().LOGI(`UnifiedPlayerService: AVSession progress updated - Position: ${currentPosition}ms, Duration: ${duration}ms`);
+        }
       }
     } catch (error) {
       LogUtils.getInstance().LOGI(`UnifiedPlayerService updateProgress error: ${error}`);
@@ -1136,15 +1272,14 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
     }
   }
 
-  private restorePlaybackPosition(song: VideoItem): void {
+  private async restorePlaybackPosition(song: VideoItem): Promise<void> {
     try {
       // 使用DataPersistenceService恢复播放进度
-      this.dataPersistence.loadPlaybackProgress(song.filePath).then(progressData => {
-        if (progressData && progressData.position > 0 && !progressData.completed) {
-          this.playerManager.seekToPosition(progressData.position.toString());
-          LogUtils.getInstance().LOGI(`UnifiedPlayerService: Restored playback position ${progressData.position}ms for ${song.name}`);
-        }
-      })
+      const progressData = await this.dataPersistence.loadPlaybackProgress(song.filePath);
+      if (progressData && progressData.position > 0 && !progressData.completed) {
+        await this.playerManager.seekToPosition(progressData.position.toString());
+        LogUtils.getInstance().LOGI(`UnifiedPlayerService: Restored playback position ${progressData.position}ms for ${song.name}`);
+      }
     } catch (error) {
       LogUtils.getInstance().LOGI(`UnifiedPlayerService restorePlaybackPosition error: ${error}`);
     }
@@ -1156,12 +1291,17 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
    */
   private async restorePersistedState(): Promise<void> {
     try {
-      console.log("Heanup2 UnifiedPlayerService: 开始恢复持久化状态");
+      console.log("Heanup2 UnifiedPlayerService: 开始快速恢复持久化状态");
       
-      // 恢复播放列表
-      const playlistData = await this.dataPersistence.loadPlaylist();
-      console.log(`Heanup2 UnifiedPlayerService: 加载到的播放列表数据: ${playlistData ? 'exists' : 'null'}`);
+      // 并行加载播放列表和播放状态,提高效率
+      const loadResults = await Promise.all([
+        this.dataPersistence.loadPlaylist().catch(() => null),
+        this.dataPersistence.loadPlayerState().catch(() => null)
+      ]);
+      const playlistData = loadResults[0];
+      const stateData = loadResults[1];
       
+      // 恢复播放列表
       if (playlistData && playlistData.songs.length > 0) {
         console.log(`Heanup2 UnifiedPlayerService: 恢复播放列表,歌曲数量=${playlistData.songs.length}, 当前索引=${playlistData.currentIndex}`);
         this.playlistModel.replaceSongs(playlistData.songs, playlistData.currentIndex);
@@ -1181,25 +1321,16 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
       }
       
       // 恢复播放状态
-      const stateData = await this.dataPersistence.loadPlayerState();
       if (stateData) {
         console.log(`Heanup2 UnifiedPlayerService: 加载到的播放状态 - playing: ${stateData.isPlaying}, paused: ${stateData.isPaused}, index: ${stateData.currentIndex}`);
         
+        // 批量更新状态,减少回调次数
         this.stateModel.updateVolume(stateData.volume);
         this.stateModel.updateSpeed(stateData.speed);
         this.stateModel.updatePlayMode(stateData.playMode);
         
-        // 恢复播放状态(isPlaying 和 isPaused)
-        if (stateData.isPlaying) {
-          console.log("Heanup2 UnifiedPlayerService: 恢复播放状态为播放中");
-          this.stateModel.updatePlayingState(true);
-        } else if (stateData.isPaused) {
-          console.log("Heanup2 UnifiedPlayerService: 恢复播放状态为暂停");
-          this.stateModel.updatePlayingState(false);
-        } else {
-          console.log("Heanup2 UnifiedPlayerService: 恢复播放状态为停止");
-          this.stateModel.updatePlayingState(false);
-        }
+        // 恢复播放状态
+        this.stateModel.updatePlayingState(stateData.isPlaying || false);
         
         // 恢复当前播放索引
         if (stateData.currentIndex >= 0) {
@@ -1212,7 +1343,7 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
         console.log("Heanup2 UnifiedPlayerService: 没有找到保存的播放状态");
       }
       
-      console.log("Heanup2 UnifiedPlayerService: 持久化状态恢复完成");
+      console.log("Heanup2 UnifiedPlayerService: 持久化状态快速恢复完成");
       
       // 设置数据恢复完成标识
       this.isDataRestored = true;
@@ -1521,25 +1652,32 @@ async initialize(context: common.UIAbilityContext): Promise<void> {
   }
 
   onPlaybackStarted(): void {
-    LogUtils.getInstance().LOGI('UnifiedPlayerService: Playback started');
+    LogUtils.getInstance().LOGI('UnifiedPlayerService: Playback started (new song)');
+    
+    // 这个回调只应该在新歌曲开始播放时被调用(通过onPrepared触发)
+    // 不应该在暂停恢复时被调用
+    
+    // 立即更新播放状态
     this.stateModel.updatePlayingState(true);
+    
+    // 启动进度定时器
     this.startProgressTimer();
     
     // 保存播放状态变化
     this.saveCurrentState();
     
-    // 延迟一点更新AVSession,确保播放器状态稳定
+    // 延迟更新AVSession,确保播放器状态稳定
     setTimeout(() => {
       this.updateSessionPlayState(true);
       // 设置当前播放模式
       this.setCurrentPlayMode();
-      LogUtils.getInstance().LOGI('UnifiedPlayerService: AVSession state updated to PLAYING with current position');
+      LogUtils.getInstance().LOGI('UnifiedPlayerService: AVSession state updated for new song playback');
     }, 200);
     
     // 播放开始时更新卡片显示播放状态
     this.updateWidgetsForPlayStateChange(true);
     
-    LogUtils.getInstance().LOGI('UnifiedPlayerService: Playback started - AVSession update scheduled');
+    LogUtils.getInstance().LOGI('UnifiedPlayerService: New song playback started successfully');
   }
 
   onPlaybackCompleted(): void {

+ 94 - 22
entry/src/main/ets/entryability/EntryAbility.ets

@@ -157,40 +157,27 @@ export default class EntryAbility extends UIAbility {
         // 注册卡片call事件监听器
         this.registerWidgetCallListeners();
         
-        // 初始化统一播放器服务(与主应用共享)
-        try {
-            await UnifiedPlayerService.getInstance().initialize(this.context);
-            hilog.info(0x0000, 'Heanup2', '✅ UnifiedPlayerService initialized successfully');
-            
-            // 延迟广播当前状态,确保卡片能接收到初始状态
-            setTimeout(() => {
-                this.broadcastCurrentPlayerState();
-            }, 2000);
-        } catch (error) {
-            hilog.error(0x0000, 'Heanup2', `❌ Failed to initialize UnifiedPlayerService: ${error}`);
-        }
+        // 异步初始化统一播放器服务,避免阻塞生命周期
+        this.initializePlayerServiceAsync();
 
         // 执行卡片注册修复(异步执行,不阻塞启动)
         this.fixWidgetRegistrationAsync();
 
-        setTimeout(async ()=>{
-            this.loadDoWant(want)
-            await this.handleParam(want)
-        },2000)
+        // 异步处理Want参数,避免阻塞生命周期
+        this.handleWantAsync(want);
 
         this.handleWeChatCallIfNeed(want)
 
         this.getHiCarStatus()
-
     }
 
     async onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): Promise<void> {
         hilog.info(0x0000, 'Heanup2', `onNewWant, want=${JSON.stringify(want)}`);
         super.onNewWant(want, launchParam);
-        this.loadDoWant(want)
-        await this.handleParam(want)
+        
+        // 异步处理Want参数,避免阻塞生命周期
+        this.handleWantAsync(want);
         this.handleWeChatCallIfNeed(want)
-
     }
 
     private handleWeChatCallIfNeed(want: Want) {
@@ -344,12 +331,26 @@ export default class EntryAbility extends UIAbility {
 
     onForeground() {
         // Ability has brought to foreground
-        hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onForeground');
+        hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onForeground start');
+        
+        // 异步处理前台逻辑,避免阻塞生命周期
+        setTimeout(() => {
+            this.handleForegroundAsync();
+        }, 10);
+        
+        hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onForeground end');
     }
 
     onBackground() {
         // Ability has back to background
-        hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onBackground');
+        hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onBackground start');
+        
+        // 异步处理后台逻辑,避免阻塞生命周期
+        setTimeout(() => {
+            this.handleBackgroundAsync();
+        }, 10);
+        
+        hilog.info(0x0000, 'Heanup2', '%{public}s', 'Ability onBackground end');
     }
 
 
@@ -535,6 +536,77 @@ export default class EntryAbility extends UIAbility {
         }
     }
 
+    /**
+     * 异步初始化播放器服务,避免阻塞生命周期
+     */
+    private initializePlayerServiceAsync(): void {
+        // 使用 setTimeout 将初始化操作移到下一个事件循环
+        setTimeout(async () => {
+            try {
+                hilog.info(0x0000, 'Heanup2', '🔄 开始异步初始化 UnifiedPlayerService');
+                await UnifiedPlayerService.getInstance().initialize(this.context);
+                hilog.info(0x0000, 'Heanup2', '✅ UnifiedPlayerService 异步初始化成功');
+                
+                // 延迟广播当前状态,确保卡片能接收到初始状态
+                setTimeout(() => {
+                    this.broadcastCurrentPlayerState();
+                }, 1000);
+            } catch (error) {
+                hilog.error(0x0000, 'Heanup2', `❌ UnifiedPlayerService 异步初始化失败: ${error}`);
+            }
+        }, 100); // 短延迟,让生命周期方法先完成
+    }
+
+    /**
+     * 异步处理前台逻辑
+     */
+    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}`);
+        }
+    }
+
+    /**
+     * 异步处理后台逻辑
+     */
+    private handleBackgroundAsync(): void {
+        try {
+            hilog.info(0x0000, 'Heanup2', '🔄 处理后台逻辑');
+            
+            // 后台时可以执行一些清理或保存操作
+            // 但要确保不会阻塞生命周期
+            
+            hilog.info(0x0000, 'Heanup2', '✅ 后台逻辑处理完成');
+        } catch (error) {
+            hilog.error(0x0000, 'Heanup2', `❌ 后台逻辑处理失败: ${error}`);
+        }
+    }
+
+    /**
+     * 异步处理Want参数,避免阻塞生命周期
+     */
+    private handleWantAsync(want: Want): void {
+        setTimeout(async () => {
+            try {
+                this.loadDoWant(want);
+                await this.handleParam(want);
+            } catch (error) {
+                hilog.error(0x0000, 'Heanup2', `❌ 处理Want参数失败: ${error}`);
+            }
+        }, 200);
+    }
+
     /**
      * 异步执行卡片注册修复
      */