我用Android构建了一个简单的音乐播放器。每首歌曲的视图都包含一个SeekBar,实现方式如下:
public class Song extends Activity implements OnClickListener,Runnable {
private SeekBar progress;
private MediaPlayer mp;
// ...
private ServiceConnection onService = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder rawBinder) {
appService = ((MPService.LocalBinder)rawBinder).getService(); // service that handles the MediaPlayer
progress.setVisibility(SeekBar.VISIBLE);
progress.setProgress(0);
mp = appService.getMP();
appService.playSong(title);
progress.setMax(mp.getDuration());
new Thread(Song.this).start();
}
public void onServiceDisconnected(ComponentName classname) {
appService = null;
}
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.song);
// ...
progress = (SeekBar) findViewById(R.id.progress);
// ...
}
public void run() {
int pos = 0;
int total = mp.getDuration();
while (mp != null && pos<total) {
try {
Thread.sleep(1000);
pos = appService.getSongPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progress.setProgress(pos);
}
}
这可以很好地工作。现在我想要一个计时器来计算歌曲播放的时间。所以我在布局中放了一个TextView
,在onCreate()
中用findViewById()
获取它,然后把它放在progress.setProgress(pos)
之后的run()
中
String time = String.format("%d:%d",
TimeUnit.MILLISECONDS.toMinutes(pos),
TimeUnit.MILLISECONDS.toSeconds(pos),
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(
pos))
);
currentTime.setText(time); // currentTime = (TextView) findViewById(R.id.current_time);
但最后一行给了我一个例外:
android.view.ViewRoot$CalledFromWrongThreadException:
只有创建了视图层次结构的原始线程才能访问它的视图。
然而,我在这里所做的事情基本上与我在SeekBar
中所做的相同-在onCreate
中创建视图,然后在run()
中接触它-它没有给我带来这种抱怨。
发布于 2011-03-02 08:29:06
您必须将更新UI的后台任务部分移动到主线程上。这里有一段简单的代码:
runOnUiThread(new Runnable() {
@Override
public void run() {
// Stuff that updates the UI
}
});
只需将此代码嵌套在后台运行的方法中,然后将实现任何更新的代码复制粘贴到代码块中间。只包含尽可能少的代码,否则就会破坏后台线程的目的。
发布于 2013-01-02 05:50:21
我通过将runOnUiThread( new Runnable(){ ..
放入run()
中解决了这个问题
thread = new Thread(){
@Override
public void run() {
try {
synchronized (this) {
wait(5000);
runOnUiThread(new Runnable() {
@Override
public void run() {
dbloadingInfo.setVisibility(View.VISIBLE);
bar.setVisibility(View.INVISIBLE);
loadingText.setVisibility(View.INVISIBLE);
}
});
}
} catch (InterruptedException e) {
e.printStackTrace();
}
Intent mainActivity = new Intent(getApplicationContext(),MainActivity.class);
startActivity(mainActivity);
};
};
thread.start();
发布于 2014-08-25 22:34:04
我的解决方案是:
private void setText(final TextView text,final String value){
runOnUiThread(new Runnable() {
@Override
public void run() {
text.setText(value);
}
});
}
在后台线程上调用此方法。
https://stackoverflow.com/questions/5161951
复制相似问题