連線藍芽裝置

獲得 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
    }
}
  • 當然,連線,讀寫函式應該在專用執行緒中完成。
  • 套接字和流物件需要