添加SeekBar
一、布局
<SeekBar
android:id="@+id/sb"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
二、在服务里添加方法:
MusicService . java
private void addSeekBar() {
//使用计时器,去不断的获取进度的代码
Timer timer = new Timer();
//设置计时器
timer.schedule(new TimerTask() {
@Override
public void run() {
int duration = player.getDuration();
int currentPosition = player.getCurrentPosition();
Message msg = MainActivity.handler.obtainMessage();
Bundle bundle = new Bundle();
bundle.putInt("duration", duration);
bundle.putInt("currentPosition", currentPosition);
msg.setData(bundle);
MainActivity.handler.sendMessage(msg);
}
}, 5, 500);
}
通过getDuration()方法可以获得时长,通过getCurrentPosition()可以获得当前播放位置。
这里需要用handler,并且使用了Bundle传递,注意是在MainActivity.java中定义的Handler。
最后,让它每隔500毫秒更新一次进度,使用了Timer 计时器。
public static Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle bundle = msg.getData();
int duration = bundle.getInt("duration");
int currentPosition = bundle.getInt("currentPosition");
sb.setMax(duration);
sb.setProgress(currentPosition);
}
};
给SeekBar设置滑动监听:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sb = (SeekBar) findViewById(R.id.sb);
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
//拖动调用
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
//当手指按下进度条,开始调用
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
//离开调用
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
int progress = seekBar.getProgress();
mi.seekTo(progress);
}
});
}
因为是通过服务这个中间者来传递数据的所以需要在服务里添加seekTo()方法:
private void seekTo(int progress) {
player.seekTo(progress);
}
在接口中添加抽象方法:
public interface MusicInterface {
void play();
void pause();
void stop();
void continuePlay();
void seekTo(int progress);
}