我正在使用 Seekbar 对音乐播放器进行编程。为了管理它,我使用带有 Runnable 的处理程序对其进行更新。它以某种方式滞后于我的 UI。我怎样才能阻止这种滞后?
创建时:
mHandler = new Handler();
当我播放歌曲时:
public static void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
我的可运行:
private static Runnable mUpdateTimeTask = new Runnable() {
public void run() {
try {
long totalDuration = songService.getTotalDuration();
int currentDuration = songService.getCurrentDuration();
// Displaying Total Duration time
player_time_length.setText(""+utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
player_time_current.setText(""+utils.milliSecondsToTimer(currentDuration));
// Updating progress bar
int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
SB_song.setProgress(currentDuration);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}catch(Exception e){}
}
};
如何防止我的应用出现这种延迟?
最佳答案
延迟是因为 Runnable
在 UI Thread
中执行。要减少或消除延迟,您必须减少在 Runnable
中执行的工作量。
您可以做的一件事是从 Runnable
中删除 long totalDuration = songService.getTotalDuration();
并将其放在外面,就像我在我的音乐播放器。
如果您包含用于将毫秒转换为人类可读时间的“utils”方法,我可以在此答案中添加更多内容。
关于java - 处理程序滞后于应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32338562/