2011-11-24 57 views
1

我正在編寫一個使用藍牙連接2個或更多設備的程序。我以BluetoothChat爲例。藍牙線程或Asynctask?

問題是,當它到達「連接」線程中的「讀取」命令時,它似乎凍結了整個程序。

我認爲這是發生了什麼,因爲沒有達到myThread.run()之後的命令,但線程內的命令是。

我做錯了什麼?

我應該切換到AsyncTask代替線程嗎?

我嘗試閱讀一些關於該主題的其他帖子,但發現它們很難遵循。 特別是,如果我應該使用AsyncTask,那麼爲什麼示例程序使用線程?

這是連接線程的代碼:

public void run() { 
     byte[] buffer = new byte[1024]; 
     int bytes; 

     // Keep listening to the InputStream while connected 
     while (true) { 
      try { 
       // Read from the InputStream 
       Log.d(TAG,"Server - BTConnectedThreadServer - run() - before read"); 
       bytes = mmInStream.read(buffer); 
       Log.d(TAG,"Server - BTConnectedThreadServer - run() - after read"); 

       // Send the obtained bytes to the UI Activity 
       mHandler.obtainMessage(BluetoothConstants.MESSAGE_READ, bytes, -1, buffer) 
         .sendToTarget(); 
       Log.d(TAG,"Server - BTConnectedThreadServer - run() - after send"); 
      } catch (IOException e) { 
       Log.d(TAG,"Server - BTConnectedThreadServer - run() - disconnected", e); 
       e.printStackTrace(); 
       BluetoothConstants.connectionLost(mHandler); 

       break; 
      } 
     } 
     Log.d(TAG,"Server - BTConnectedThreadServer - run() - Exited Loop"); 
    } 

的「前閱讀」日誌注意出現,但沒有人這樣做。 它永遠不會返回到主線程。

回答

2

myThread.run()將仍然是相同的線程上運行,你想myThread.start(),如果那不解決這個問題,表現出一定的代碼

+0

Grrrrr。非常感謝。現在效果很好。 – theblitz

+0

非常感謝...拯救了我的生命... – ValayPatel

1

您應該使用myThread.start()而不是myThread.run()來啓動線程。

+0

Grrrrr。非常感謝。現在效果很好。 – theblitz