2 nana4ever nana4ever 于 2012.12.12 17:18 提问

Android: 更新线程中的UI

我使用以下代码更新一个seekbar。问题是每当seekBar.setProgress()被调用时,UI上其它元素就被冻结。因此我想用另外一个线程在主线程中来更新 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;
}

我不明白为什么会出现这样的问题,如何进行?

2个回答

cytown
cytown   2012.12.12 17:28
已采纳
sendMessageDelayed(msg, 100 - (pos % 1000));

更新频率太快,你应该是写错了吧?

sendMessageDelayed(msg, 1000 - (pos % 1000));
hooopo
hooopo 哈 还真有可能呢
5 年多之前 回复
curie_87
curie_87   2012.12.13 17:16

Activities有一个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;
}
Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!