2011-11-24 55 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