perf: 优化视频切换的内存管理
- 在 VideoPlayer.release() 中添加 reset() 调用,确保 MediaPlayer 完全重置 - 添加专门的 IllegalStateException 处理,捕获非法状态异常 - 使用 finally 块确保状态变量始终被重置 - 在 onCompletion() 中添加内存使用监控日志 - 记录当前内存使用量和最大可用内存(以 MB 为单位) 这些优化确保了: 1. MediaPlayer 资源被正确释放,避免内存泄漏 2. 即使在异常情况下也能正确清理状态 3. 可以通过日志监控应用的内存使用情况 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
2b6f8145df
commit
9511cc3de9
2 files changed
+14
-3
No files matched your search
@@ -186,6 +186,12 @@ public class AutoWallpaperService extends WallpaperService {
|
||||
public void onCompletion() {
|
||||
fileLogger.log(TAG, "Video completed, switching to next media");
|
||||
|
||||
// 记录内存使用情况
|
||||
Runtime runtime = Runtime.getRuntime();
|
||||
long usedMemory = (runtime.totalMemory() - runtime.freeMemory()) / 1024 / 1024;
|
||||
long maxMemory = runtime.maxMemory() / 1024 / 1024;
|
||||
fileLogger.log(TAG, "Memory usage: " + usedMemory + " MB / " + maxMemory + " MB");
|
||||
|
||||
// 检查 Surface 是否仍然有效
|
||||
if (!visible) {
|
||||
fileLogger.log(TAG, "Surface not visible, skipping auto-switch");
|
||||
|
||||
@@ -158,14 +158,19 @@ public class VideoPlayer {
|
||||
if (mediaPlayer.isPlaying()) {
|
||||
mediaPlayer.stop();
|
||||
}
|
||||
mediaPlayer.reset(); // 重置 MediaPlayer 到空闲状态
|
||||
mediaPlayer.release();
|
||||
if (fileLogger != null) fileLogger.log(TAG, "MediaPlayer released");
|
||||
} catch (IllegalStateException e) {
|
||||
// MediaPlayer 已经处于非法状态,继续清理
|
||||
if (fileLogger != null) fileLogger.warn(TAG, "MediaPlayer already released: " + e.getMessage());
|
||||
} catch (Exception e) {
|
||||
if (fileLogger != null) fileLogger.error(TAG, "Error releasing MediaPlayer", e);
|
||||
} finally {
|
||||
mediaPlayer = null;
|
||||
isPrepared = false;
|
||||
hasError = false; // 重置错误状态
|
||||
}
|
||||
mediaPlayer = null;
|
||||
isPrepared = false;
|
||||
hasError = false; // 重置错误状态
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user