连接蓝牙设备
获得 BluetoothDevice 后,你可以与之通信。通过使用套接字输入\输出流执行此类通信:
这些是蓝牙通信建立的基本步骤:
1)初始化套接字:
private BluetoothSocket _socket;
//...
public InitializeSocket(BluetoothDevice device){
try {
_socket = device.createRfcommSocketToServiceRecord(<Your app UDID>);
} catch (IOException e) {
//Error
}
}
2)连接到插座:
try {
_socket.connect();
} catch (IOException connEx) {
try {
_socket.close();
} catch (IOException closeException) {
//Error
}
}
if (_socket != null && _socket.isConnected()) {
//Socket is connected, now we can obtain our IO streams
}
3)获取套接字输入\输出流
private InputStream _inStream;
private OutputStream _outStream;
//....
try {
_inStream = _socket.getInputStream();
_outStream = _socket.getOutputStream();
} catch (IOException e) {
//Error
}
输入流 - 用作输入数据通道(从连接的设备接收数据)
输出流 - 用作输出数据通道(将数据发送到连接的设备)
完成第 3 步后,我们可以使用以前初始化的流在两个设备之间接收和发送数据:
1)接收数据(从套接字输入流读取)
byte[] buffer = new byte[1024]; // buffer (our data)
int bytesCount; // amount of read bytes
while (true) {
try {
//reading data from input stream
bytesCount = _inStream.read(buffer);
if(buffer != null && bytesCount > 0)
{
//Parse received bytes
}
} catch (IOException e) {
//Error
}
}
2)发送数据(写入输出流)
public void write(byte[] bytes) {
try {
_outStream.write(bytes);
} catch (IOException e) {
//Error
}
}
- 当然,连接,读写函数应该在专用线程中完成。
- 套接字和流对象需要