動的更新seekBar
2978 ワード
public class MediaPlayerActivity extends Activity implements Runnable{
/** Called when the activity is first created. */
private MediaPlayer mPlayer;
private ImageButton mPlay;
private ImageButton mPause;
private SeekBar mSeekBar;
private int total;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPlay = (ImageButton) findViewById(R.id.play);
mPause = (ImageButton) findViewById(R.id.pause);
mSeekBar = (SeekBar) findViewById(R.id.seekbar);
mPlayer = MediaPlayer.create(this,R.raw.mp3_file_name);
mSeekBar.setProgress(0);
total = mPlayer.getDuration();
mPause.setVisibility(View.INVISIBLE);
mPlay.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mPlayer.start();
mSeekBar.setMax(total);
mPlay.setVisibility(View.INVISIBLE);
mPause.setVisibility(View.VISIBLE);
}
});
mPause.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(mPlayer.isPlaying()){
mPlayer.pause();
mPlay.setVisibility(View.VISIBLE);
mPause.setVisibility(View.INVISIBLE);
}
}
});
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if(fromUser){
mPlayer.seekTo(progress);
mSeekBar.setProgress(progress);
}
}
});
Thread currentThread = new Thread(this);
currentThread.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
while(mPlayer != null){
int currentPosition = mPlayer.getCurrentPosition();
Message msg = new Message();
msg.what = currentPosition;
threadHandler.sendMessage(msg);
}
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private Handler threadHandler = new Handler(){
public void handleMessage(Message msg){
//super.handleMessage(msg);
//txt.setText(Integer.toString(msg.what));
mSeekBar.setProgress(msg.what);
}
};
}