2016-10-06 94 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();