Android – progress dialog usage of thread

This is my code,

public ProgressDialog loadingdialog;
public void ShowManager() {
    //do something
}
public void startScan() {
      loadingdialog = ProgressDialog.show(WifiManagementActivity.this,
                                              "","Scanning Please Wait",true);
      new Thread() {
          public void run() {
              try {
                    sleep(4000);
                    ShowManager();

              } catch(Exception e) {
                    Log.e("threadmessage",e.getMessage());
              }
              loadingdialog.dismiss();
          }
      }.start();
    }

startScan();

A basic ProgressDialog show function, but an error is found on the line calling showmanager(),

01-07 23:11:36.081: ERROR/threadmessage(576): Only the original thread 
that created a view hierarchy can touch its views.

Edit:

Showmanager () is a function that changes view elements. Soon,

  public void ShowManager() 
  {
      TextView mainText = (TextView) findViewById(R.id.wifiText);
      mainText.setText("editted");

  }

resolvent:

I found the answer. I don't want to answer my own question, but maybe this will help others. In a separate thread, we can't update most UI objects. We have to create a handler and update the view in it

public ProgressDialog loadingdialog;
  private Handler handler = new Handler() {
          @Override
              public void handleMessage(Message msg) {
              loadingdialog.dismiss();
              ShowManager();

          }
      };
  public void ShowManager()
  {
      TextView mainText = (TextView) findViewById(R.id.wifiText);
      mainText.setText("editted");
  }
  public void startScan() {
      loadingdialog = ProgressDialog.show(WifiManagementActivity.this,
                                          "","Scanning Please Wait",true);
      new Thread() {
          public void run() {
              try {
                  sleep(4000);
                  handler.sendEmptyMessage(0);

              } catch(Exception e) {
                  Log.e("threadmessage",e.getMessage());
              }
          }
      }.start();
  }

  startScan();

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>