我有一个使用Android媒体播放器播放MIDI文件的应用程序。我将textview作为一个计时器,它将根据播放进度动态改变。然而,由于它陷入了2s标记,这是非常错误的
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);
}
答案 0 :(得分:0)
您需要在单独的线程中执行此操作,并通过runOnUiThread通过runnable发回GUI线程以设置计时器的文本。因为你可能毫无例外地设置了GUI组件的文本,我假设你现在没有这样做。
请发布完整的方法。通过完整的方法,我们可以帮助追踪它在2秒标记处停止的原因。