这是来自Google示例代码BluetoothChat的标准代码。 BluetoothChatService.java
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (mState == STATE_CONNECTED) {
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();
break;
}
}
}
我尝试使用
连接设备时mChatService.connect(device, false);
我得到以下异常
java.io.IOException: bt socket closed, read return: -1
at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:872)
at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)
at java.io.InputStream.read(InputStream.java:163)
任何帮助都将不胜感激。
答案 0 :(得分:0)
您是否在Android清单中包含了针对您的应用的蓝牙权限?
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
答案 1 :(得分:0)
我猜问题是mmSocket.connect()
尝试通过反映获取方法createRfcommSocket
。
以下是基于Google示例代码BluetoothChat的示例。
// Make a connection to the BluetoothSocket
try {
Thread.sleep(500);
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
OutputStream os = mmSocket.getOutputStream();
// Here: connect success
} catch (Exception e) {
Log.i(TAG, "Lost 1st try; SPP connect[2]");
try {
mmSocket.close();// close the current socket
mmSocket = null;
Thread.sleep(500L); // wait for a while
mmSocket = (BluetoothSocket) mmDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(mmDevice, 1); // The key method !
mmSocket.connect();
OutputStream os = mmSocket.getOutputStream();
// Here: connect success
synchronized (ESDevice.this) {
mSPPConnectThread = null;
}
connected(mmSocket, mmDevice); // begin connected thread
} catch (Exception e2) {
Log.e(TAG, "Lost 2nd try. Connect fail", e2);
connectionFailed();
return;
}
return;
}
答案 2 :(得分:0)
在您<dsp:valueof param="amount" converter="currency" locale="en_US" />
的构造函数中传递socket之前,套接字似乎已关闭。
Google示例中有一个棘手的问题,在mConnectedThread
中,当socket实际连接时,我们将mConnectThread设为null,并且下一个代码将不会执行:
mConnectThread
这意味着将跳过关闭套接字的if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
方法。
基本上,请确保在连接套接字后不要在cancel()
中调用close()
方法。