Android AlertDialog 在 bluetoothsocket.connect() 之后才会显示

Android AlertDialog won't show until after bluetoothsocket.connect()

我有一个AlertDialog设置在bluetoothsocket.connect()之前显示,这是一种屏蔽方式。但是,AlertDialog 直到 bluetoothsocket.connect() 方法完成后才会显示。

myalertdialog.show();
// Dialog is not shown.
mybluetoothsocket.connect();  // This blocks and takes a few seconds to run.
// Dialog is shown.

是什么导致了这种行为?

如果您的 bluetoothsocket.connect() 正在阻塞,正如您所说的那样,您应该将其置于 UI 主线程之外。您可以做的是将它放在 AsyncTask 中。您的 myalertdialog.show() 可以在调用您的 AsyncTask 之前立即执行。然后在AsyncTaskonPostExecute().

中调用myalertdialog.hide()

因为 bluetoothsocket.connect 块 UI 在单独的线程上调用它

final Handler mHandler = new Handler();// This statement is to be called by the main thread

                myalertdialog.show();

                Thread t = new Thread(
                        new Runnable(){

                            public void run()
                            {

                                mybluetoothsocket.connect(); 
                                mHandler.post(new Runnable(){

                                    public void run()
                                    {
                                        //ProgressDialog.dismiss();
                                    }
                                });
                            }});
                t.start();