2016-10-06 128 views
1

我有一个AlertDialog设置为bluetoothsocket.connect()之前显示,这是一种阻止方法。但是,AlertDialog直到bluetoothsocket.connect()方法结束后才显示。Android AlertDialog不会显示,直到bluetoothsocket.connect()

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

什么可能导致此行为?

回答

1

如果你的bluetoothsocket.connect()被阻塞,你说的是,你应该把它放在UI主线程之外。你可以做的是把它放进AsyncTask。您可以在致电AsyncTask之前执行您的myalertdialog.show()。然后在AsyncTaskonPostExecute()中拨打myalertdialog.hide()

+0

你说得对,阻塞代码不应该在UI线程上运行。正如你所提到的那样,我将它移到了一个AsyncTask中,它现在可以完美运行。谢谢!! – pcdangio

0

由于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();