我是对象输入流和对象输出流的新手,但我必须使用它们通过蓝牙发送字符串。每当我尝试连接时,两部手机都会冻结然后崩溃。我使用了调试器,它在程序冻结之前停在的最后一行是:tmpIn = new ObjectInputStream(socket.getInputStream());
这是我的连接线程:
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final ObjectInputStream mmInStream;
private final ObjectOutputStream mmOutStream;
private FileOutputStream mmFileOut = null;
public ConnectedThread(BluetoothSocket socket, String socketType) {
Log.d(TAG, "create ConnectedThread: " + socketType);
mmSocket = socket;
ObjectInputStream tmpIn = null;
ObjectOutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
//input stream
//mmFileIn = new FileInputStream("t.tmp");
tmpIn = new ObjectInputStream(socket.getInputStream());
//output stream
mmFileOut = new FileOutputStream("t.tmp");
tmpOut.flush();
tmpOut = new ObjectOutputStream(mmFileOut);
tmpOut.writeObject(socket.getOutputStream());
}catch (FileNotFoundException fnfe){
System.out.println("FileOutPutStream: "+ fnfe);
}catch (IOException ie){
System.out.print("ObjectOutputStream: " + ie);
}catch (Exception e){
System.out.print(e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
// Start the service over to restart listening mode
BluetoothChatService.this.start();
break;
}
}
}
/**
* Write to the connected OutStream.
*
* @param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
mHandler.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
我在某处看到它可能与在我的对象输出流上使用.flush()有关,我正确使用它吗?
答案 0 :(得分:2)
构造函数中的代码在UI线程上运行。将其移至run()。