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
レイアウトに を配置し、 でそれを取得しfindViewById()
、の後にonCreate()
これを配置します。run()
progress.setProgress(pos)
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()
が、この苦情は発生しません。
ベストアンサー1
UI を更新するバックグラウンド タスクの部分をメイン スレッドに移動する必要があります。これには簡単なコードがあります。
runOnUiThread(new Runnable() {
@Override
public void run() {
// Stuff that updates the UI
}
});
ドキュメントActivity.runOnUiThread
。
これをバックグラウンドで実行されているメソッド内にネストし、ブロックの途中で更新を実装するコードをコピーして貼り付けます。含めるコードは可能な限り最小限にしてください。そうしないと、バックグラウンド スレッドの目的が達成されなくなります。