gpt4 book ai didi

Android:从线程更新用户界面

转载 作者:行者123 更新时间:2023-11-29 16:14:04 26 4
gpt4 key购买 nike

要更新搜索栏,我使用以下代码:我的问题是,无论何时调用 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;
}

最佳答案

Activity 有一个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;

关于Android:从线程更新用户界面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10801804/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com