0

单击按钮后,我正在尝试执行以下操作:

case R.id.bcheckConnection:
        if (IPok()) {
            PlcState.ErrPlc = false;
            Constant.adressIpPlc = adresIp.getText().toString();

            final ProgressDialog dialog =     ProgressDialog.show(Main.this, "", "Trying to connect...");
            new Thread(new Runnable() {
                public void run() {
                    timeout = network.testConnection(Constant.adressIpPlc, 102, 20000);
                    dialog.dismiss();
                }
            }).start();

            if (timeout > -1) {
                PlcState.ErrPlc = false;

                stanPolaczenia.setText("Connection established. Timeout = ");
                stanTimeout.setText(Long.toString(timeout));
                currentIp.setText(Constant.adressIpPlc);

            } else {
                PlcState.ErrPlc = true;
                stanPolaczenia.setText("Error");
                stanTimeout.setText("");
                currentIp.setText(Constant.adressIpPlc);
            }
        } else {
            Toast.makeText(Main.this, "Wrong IP", Toast.LENGTH_LONG).show();
        }
        break;

那么是否可以在线程停止运行后更改文本?

4

1 回答 1

1

您可以使用Thread.join()阻塞当前线程,直到给定线程完成:

Thread myThread = new Thread(new Runnable() {
    public void run() {
       // Do something
    }
});
myThread.start();

// Do some things

// and block current thread until myThread is finished
myThread.join();

// Continue execution after myThread got finished

编辑:正如@Eric 在问题评论中已经提到的那样:对于您的(示例)情况,使用AsyncTask. 它有两个事件(在 UI 线程上调用),因此您可以使用进度更新和任务完成时间来更新您的 UI。有关AsyncTask示例,请参见:AsyncTask Android 示例

于 2013-01-03T23:28:15.420 回答