我正在开发一款Android蓝牙应用程序,旨在通过我们创建的设备使用蓝牙说话,我成功地使所有设备都能在Android 3+上运行,但似乎是android 2.3.x(这是我们的最低要求)不像其他人那样行事。我还在华为Ascend P1上再现了相同的行为。
在Android方面发生的一切都是正常的,我连接到设备并且如果我没有配对就会发出配对请求,我会在内部和外部检索,但是当我使用它们时,它们就像我说的那样对我自己的环回。输出流上写入的所有内容都在输入流上读取。当然,设备看不到任何东西(似乎它甚至不知道连接了Android手机)。
以下是我的来源的一些代码示例(大部分内容与Android文档中描述的完全相同):
连线:
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
btSpeaking = true;
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
tmp = device.createInsecureRfcommSocketToServiceRecord(BluetoothUuid.declareUuid.getUuid());
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
mConnected = new ConnectedThread(mmSocket);
mConnected.start();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
阅读主题
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
WSLog.e(tag, e.getMessage(), e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
try {
writeSocket(RESET, empty);
} catch (IOException e1) {
return;
}
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
for (int size = 0; size < framesize;) {
int read = mmInStream.read(frame, size, frame.length - size);
if (read < 0) {
return;
}
size = size + read;
}
} catch (IOException e) {
return;
}
}
}
写套接字:
private void writeSocket(byte comm, byte[] data) throws IOException {
ByteBuffer bf = ByteBuffer.allocate(1 + data.length);
bf.put(PROTO);
bf.put(comm);
bf.put(data);
mmOutStream.write(bf.array());
}
我真的希望我没有做出明显错误的事情,但由于我无法理解为什么它不起作用我别无选择,只能寻求帮助。
谢谢, 马丁