首先在Activity中设置相应参数,如下:
private ProgressBar pbar;
private static final int REFRESH_TIME = 1;
private long mPosOverride = -1;
// Handler used to update the current time
private TimeHandler mTimeHandler;
private boolean mIsPaused = false;
实现刷新进度的方法:
private long refreshCurrentTime() {
if (mService == null) {
return 500;
}
try {
final long pos = mPosOverride < 0 ? MusicUtils.position()
: mPosOverride;
if (pos >= 0 && MusicUtils.duration() > 0) {
// refreshCurrentTimeText(pos);
final int progress = (int) (1000 * pos / MusicUtils.duration());
pbar.setProgress(progress);
} else {
pbar.setProgress(1000);
}
// calculate the number of milliseconds until the next full second,
// so
// the counter can be updated at just the right time
final long remaining = 1000 - pos % 1000;
// approximate how often we would need to refresh the slider to
// move it smoothly
int width = pbar.getWidth();
if (width == 0) {
width = 320;
}
final long smoothrefreshtime = MusicUtils.duration() / width;
if (smoothrefreshtime > remaining) {
return remaining;
}
if (smoothrefreshtime < 20) {
return 20;
}
return smoothrefreshtime;
} catch (final Exception ignored) {
}
return 500;
}
/**
* @param delay
* When to update
*/
private void queueNextRefresh(final long delay) {
if (!mIsPaused) {
final Message message = mTimeHandler.obtainMessage(REFRESH_TIME);
mTimeHandler.removeMessages(REFRESH_TIME);
mTimeHandler.sendMessageDelayed(message, delay);
}
}
实现Handler:
/**
* Used to update the current time string
*/
private static final class TimeHandler extends Handler {
private final WeakReference<MusicWaveActivity> mAudioPlayer;
/**
* Constructor of <code>TimeHandler</code>
*/
public TimeHandler(final MusicWaveActivity player) {
mAudioPlayer = new WeakReference<MusicWaveActivity>(player);
}
@Override
public void handleMessage(final Message msg) {
switch (msg.what) {
case REFRESH_TIME:
final long next = mAudioPlayer.get().refreshCurrentTime();
mAudioPlayer.get().queueNextRefresh(next);
break;
default:
break;
}
}
};
最后在Activity 中的操作;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.home);
mTimeHandler = new TimeHandler(this);
}
@Override
protected void onDestroy() {
mIsPaused = false;
mTimeHandler.removeMessages(REFRESH_TIME);
}
@Override
protected void onResume() {
queueNextRefresh(1);
}