简体   繁体   English

仅在线程终止后才显示进度对话框

[英]Progress Dialog is shown only after Thread terminates

I'm trying to connect to a TCP/IP socket in a thread the moment my app is opened, and would like to show a progress dialog while connecting.我正在尝试在我的应用程序打开时连接到线程中的 TCP/IP 套接字,并希望在连接时显示进度对话框。 The problem is that the thread is always executed before the progress dialog is shown, which means that it is shown only after the socket connection has actually happened (or failed).问题是线程总是在显示进度对话框之前执行,这意味着它只有在套接字连接实际发生(或失败)之后才会显示。

public static boolean startConnection (Context c) {

    boolean[] ret = new boolean[1];

    ProgressDialog progressDialog = new ProgressDialog(c);
    progressDialog.setMessage("Connecting...");
    progressDialog.show();

    Thread t = new Thread() {
        @Override
        public void run() {
            try {
                clientSocket = new Socket();
                clientSocket.connect(new InetSocketAddress(SERVER_IP, SERVER_PORT), 5000);
                ret[0] = true;
            }
            catch (IOException e) {
                e.printStackTrace();
                ret[0] = false;
            }
            ((Activity)c).runOnUiThread(progressDialog::dismiss);
        }
    };

    t.start();
    try {
        t.join();
    } 
    catch (InterruptedException e) {
        e.printStackTrace();
    }

    return ret[0];

}

And I'm invoking startConnection in the onStart() method:我在onStart()方法中调用startConnection

protected void onStart() {

    super.onStart();
    if (ConnectionHandler.startConnection(this)) {
        goToMainActivity();
    }
    else {
        Toast.makeText(this, "Connection error.", Toast.LENGTH_LONG).show();
    }

}
   

How can I make it so that the progress dialog is shown before the thread actually starts?如何在线程实际启动之前显示进度对话框?

t.join(); waits on the UI main thread until second thread t finishes, that's the reason your code is blocking the UI thread and the dialog doesn't appear.在 UI 主线程上等待,直到第二个线程 t 完成,这就是您的代码阻塞 UI 线程并且没有出现对话框的原因。

In addition you can't call progressDialog.dismiss() ;此外,您不能调用progressDialog.dismiss() on the t thread, all code that interacts with the UI must be called on the main thread, you can try tom call it using runOnUIThread() activity method在 t 线程上,所有与 UI 交互的代码都必须在主线程上调用,您可以尝试使用runOnUIThread()活动方法调用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM