它说必须调用looper.prepare

时间:2017-06-17 18:49:55

标签: java android multithreading

我在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();
            }
        }
    }
}

}

2 个答案:

答案 0 :(得分:1)

错误是因为您正在从其他线程更新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
               }
          });
 };

答案 1 :(得分:0)

您应该只在Main Looper上运行进度条。 添加

    handler = new Handler(context.getMainLooper()) {
.....
}

应该工作。