gpt4 book ai didi

java - 它说必须调用looper.prepare

转载 作者:行者123 更新时间:2023-12-02 12:51:11 28 4
gpt4 key购买 nike

我正在 MainActivity 处理程序的帮助下更新进度条但它给出了错误:无法在未调用 Looper.prepare() 的线程内创建处理程序

Error

public class MainActivity extends AppCompatActivity {
ProgressBar progressBar;
Handler handler;
Thread thread;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
thread = new Thread(new MyThread());
thread.start();
handler = new Handler() {
@Override
public void handleMessage(Message msg) {
progressBar.setProgress(msg.arg1);
}
};


}

class MyThread implements Runnable {

@Override
public void run() {
Message message = Message.obtain();

for (int i = 0; i < 100; i++) {
message.arg1 = i;
handler.sendMessage(message);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

}

最佳答案

该错误是因为您正在从不同的线程更新 UI。所以你应该做的就是在主 ui 线程上调用 update 方法

handler = new Handler() {
@Override
public void handleMessage(Message msg) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// Do something on UiThread
// update progress
}
});
};

关于java - 它说必须调用looper.prepare,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44608236/

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