我在笔记本电脑上运行蓝牙服务器,在我的应用程序中运行蓝牙客户端。该应用程序愉快地连接到服务器,可以完美地写入数据。但是,当我添加read()功能时,应用程序崩溃了。看起来这个命令阻止了UI线程,但我无法弄清楚为什么,因为我以为我是在一个单独的线程中运行它。我没有很多线程经验,所以我假设我错过了一些重要的东西。有人有任何线索吗?
主要活动:
public void startBluetoothConnection(BluetoothDevice device){
alreadyConnecting = true;
btConnection = new ConnectionService(this, device);
manageConnectionService = btConnection.startConnection();
//This line causes the problem...
manageConnectionService.read();
}
ManageConnectionService:
public class ManageConnectionService extends Thread {
private final BluetoothSocket mSocket;
private final InputStream mInStream;
private final OutputStream mOutStream;
private Context mContext;
public static final String tag = "MANAGECONNECTIONSERVICE";
public ManageConnectionService(Context context, BluetoothSocket socket){
mContext = context;
mSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try{
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
}catch(IOException e){
Log.e(tag, e.toString());
}
mInStream = tmpIn;
mOutStream = tmpOut;
}
public void read() {
byte[] buffer = new byte[1024];
int bytes;
int m;
StringBuilder message = new StringBuilder(100);
while (true) {
try {
m = mInStream.read();
Log.i("MESSAGE RECEIVED", buffer.toString() + " length = " + m);
// if it's the end of the message...
if (m == 37) {
Log.i(tag, "End of message " + message.toString());
//Do stuff here
message = new StringBuilder(100);
} else {
message.append(Character.toString((char) m));
}
} catch (IOException e) {
Log.e(tag, e.toString());
break;
}
}
}
public void write(byte[] bytes){
try{
mOutStream.write(bytes);
Log.i(tag, "Sent message!");
}catch (IOException e){
Log.e(tag, e.toString());
}
}
public void cancel(){
try{
mSocket.close();
}catch (IOException e){
Log.e(tag, e.toString());
}
}
}