在调用活动“Main”开头使用ProgressDialog有几个功能

时间:2012-03-20 01:37:59

标签: android multithreading handler progressdialog

我真的搜索了如何在我的活动“Main”的开头显示加载,但同时这个活动必须调用一些函数,所以我使用了这段代码:

ProgressDialog bar;

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); 

        loading();
}


private void loading() {
          bar = ProgressDialog.show(this, "Please wait",
                  "Long operation starts...", true);

          new Thread((new Runnable() {
              @Override
              public void run() {
                  bar.setMessage("Loading...");
                  initLocalisation();
                      initTabhost();
              }
          })).start();
  }

public void msgbox(String str) {
        Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
    }

实际上它显示了以下错误:

FATAL EXCEPTION: Thread-99
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:121)
at android.widget.Toast$TN.<init>(Toast.java:317)
at android.widget.Toast.<init>(Toast.java:91)
at android.widget.Toast.makeText(Toast.java:233)
at com.main.Main.msgbox(Main.java:519)
at com.main.Main.updateWithNewLocation(Main.java:148)
at com.main.Main.initLocalisation(Main.java:204)
at com.main.Main$4.run(Main.java:172)
at java.lang.Thread.run(Thread.java:856)

1 个答案:

答案 0 :(得分:0)

您无法从非UI线程访问UI。您需要阅读题为Painless Threading

的文件