我有一个使用 android 媒体播放器播放 MIDI 文件的应用程序。我制作了一个 textview 作为计时器,它将根据播放进度动态变化。但是,它非常有问题,因为它卡在了 2 秒标记处
class progressTrack extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... arg0) {
ToggleButton mStartStop;
int currentPosition=0;
int total=mediaPlayer.getDuration();
TextView timer=(TextView) findViewById(R.id.timer);
while (mediaPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mediaPlayer
.getCurrentPosition();
double seconds=currentPosition/1000;
int time= (int) Math.round(seconds);
String timeS=Integer.toString(time);
Log.d("Time",timeS);
timer.setText(timeS+"s");
fSlider.setProgress(currentPosition);
} catch (InterruptedException e) {
} catch (Exception e) {
}
OnSeekBarChangeListener listener = new OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) { }
public void onStartTrackingTouch(SeekBar seekBar) { }
public void onProgressChanged(SeekBar seekBar,
int progress,
boolean fromUser) {
if(fromUser)
mediaPlayer.seekTo(progress);
}
};
fSlider.setOnSeekBarChangeListener(listener);
}
时间在 Logcat 上确实显示正确,但为什么它不会在 textview 上更改?
解决了:
protected void onPostExecute(String result) {
ScheduledExecutorService myScheduledExecutorService = Executors.newScheduledThreadPool(1);
myScheduledExecutorService.scheduleWithFixedDelay(
new Runnable(){
@Override
public void run() {
monitorHandler.sendMessage(monitorHandler.obtainMessage());
}},
200, //initialDelay
200,
TimeUnit.MILLISECONDS//delay TimeUnit.MILLISECONDS
);
}
}
Handler monitorHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
startUI();
}
};
void startUI(){
Log.d("UI", "Started player UI");
ToggleButton mStartStop;
int currentPosition=0;
int total=mediaPlayer.getDuration();
TextView timer=(TextView) findViewById(R.id.timer);
if(mediaPlayer.isPlaying())
try {
currentPosition = mediaPlayer
.getCurrentPosition();
double seconds=currentPosition/1000;
int time= (int) Math.round(seconds);
String timeS=Integer.toString(time);
timer.setText(timeS+"s");
Log.d("position",timeS);
fSlider.setProgress(currentPosition);
} catch (Exception e) {
}
OnSeekBarChangeListener listener = new OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) { }
public void onStartTrackingTouch(SeekBar seekBar) { }
public void onProgressChanged(SeekBar seekBar,
int progress,
boolean fromUser) {
if(fromUser)
mediaPlayer.seekTo(progress);
}
};
fSlider.setOnSeekBarChangeListener(listener);
mStartStop= (ToggleButton) findViewById(R.id.toggleButton1);
mStartStop.setOnCheckedChangeListener(pauseListener);
}