nana4ever
2012-12-12 09:18
采纳率: 95.8%
浏览 2.9k

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条回答 默认 最新

  • Billy_崔海斌 2012-12-12 09:28
    已采纳
    sendMessageDelayed(msg, 100 - (pos % 1000));
    

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

    sendMessageDelayed(msg, 1000 - (pos % 1000));
    
    打赏 评论
  • Curie-87 2012-12-13 09: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;
    }
    
    打赏 评论

相关推荐 更多相似问题