1

要更新搜索栏,我使用以下代码:我的问题是,只要调用 seekBar.setProgress(),UI 上的其他元素就会冻结,所以我希望有一个不同的线程来更新 main 中的 seekBar线。

如何进行 ?

    private Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        try {
            int pos;
            switch (msg.what) {
            case SHOW_PROGRESS:
                pos = setProgress();
                if (!mDragging && mBoundService.isPlaying()) {
                    msg = obtainMessage(SHOW_PROGRESS);
                    sendMessageDelayed(msg, 100 - (pos % 1000));
                }
                break;
            }
        } catch (Exception e) {

        }
    }
};

private int setProgress() {
    if (mBoundService == null || mDragging) {
        return 0;
    }
    int position = mBoundService.getCurrentPosition();
    int duration = mBoundService.getDuration();
    if (sliderSeekBar != null) {
        if (duration > 0) {
            // use long to avoid overflow
            long pos = 1000L * position / duration;
            sliderSeekBar.setProgress((int) pos);
        }
    }

    if (sliderTimerStop != null)
        sliderTimerStop.setText(stringForTime(duration));
    if (sliderTimerStart != null)
        sliderTimerStart.setText(stringForTime(position));

    return position;
}
4

1 回答 1

4

活动有一个runOnUiThread方法允许单独的线程更新 UI 组件。你的setProgress方法最终看起来像:

private int setProgress() {

    if (mBoundService == null || mDragging) {
        return 0;
    }
    final int position = mBoundService.getCurrentPosition();
    final int duration = mBoundService.getDuration();

    runOnUiThread(new Runnable(){

        @Override
        public void run(){

            if (sliderSeekBar != null) {
                if (duration > 0) {
                    // use long to avoid overflow
                    long pos = 1000L * position / duration;

                    sliderSeekBar.setProgress((int) pos);
                }
            }

            if (sliderTimerStop != null)
                sliderTimerStop.setText(stringForTime(duration));
            if (sliderTimerStart != null)
                sliderTimerStart.setText(stringForTime(position));
        }
    });

    return position;

}

于 2012-05-29T15:12:56.020 回答