我正在制作音频播放器应用,我希望能够刷新显示当前播放位置的搜索栏和显示时间的文本视图。我能够做到这一点,但有一个问题。当seekbar和textview更新时,每秒都有一个小的音频滞后。它就像是在视图更新时每秒暂停一段时间。
这是我的更新程序类
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.TimeUnit;
class refreshSeekBar extends Thread{
private Handler mainHandler = new Handler(Looper.getMainLooper());
@Override
public void run() {
startRefreshingSeekBar();
}
private void startRefreshingSeekBar(){
Global.scheduledFuture = Global.scheduledExecutorService.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
long S = Global.mediaPlayer.getCurrentPosition();
S = S/1000;
long M = S/60;
S = S%60;
String SS = ""+S;
String MM = ""+M;
if((S/10)<1){
SS = "0"+SS;
}
if((M/10)<1){
MM = "0"+MM;
}
final String MMM = MM;
final String SSS = SS;
mainHandler.post(new Runnable() {
@Override
public void run() {
Global.seekBar.setProgress(Global.mediaPlayer.getCurrentPosition());
Global.textCurrentDuration.setText(MMM+":"+SSS);
}
});
}
},0,1000, TimeUnit.MILLISECONDS);
}
}
答案 0 :(得分:1)
我能够解决问题。我没有在搜索栏的OnSeekBarChangeListener中使用boolean fromUser来防止在以编程方式设置进度时调用它。每当进展更新时,它都在寻找mediaPlayer,因此也就是滞后。
答案 1 :(得分:0)
这就是我在我的应用程序中执行它的方式,它运行时没有任何延迟,我的代码将毫秒转换为分钟和秒,而不使用if语句。
@Override
public void run() {
currentPosition = mPlayer.getCurrentPosition();
total = mPlayer.getDuration();
while (mPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
runOnUiThread(new Runnable() {
@Override
public void run() {
// This code will always run on the UI thread, therefore is safe to modify UI elements.
String currTime = String.format("%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(currentPosition),
TimeUnit.MILLISECONDS.toSeconds(currentPosition) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(currentPosition))
);
currentPos.setText(currTime);
}
});
}
}