BluetoothSocket是一个用于在Android设备之间进行蓝牙通信的类。它提供了一种通过蓝牙连接进行数据传输的方法,BluetoothSocket的connect方法代码如下:
//packages/modules/Bluetooth/framework/java/android/bluetooth/BluetoothSocket.java
public final class BluetoothSocket implements Closeable {
public void connect() throws IOException {
if (mDevice == null) throw new IOException("Connect is called on null device");
try {
if (mSocketState == SocketState.CLOSED) throw new IOException("socket closed");
IBluetooth bluetoothProxy =
BluetoothAdapter.getDefaultAdapter().getBluetoothService();
if (bluetoothProxy == null) throw new IOException("Bluetooth is off");
IBluetoothSocketManager socketManager = bluetoothProxy.getSocketManager(); //取得IBluetoothSocketManager
if (socketManager == null) throw new IOException("bt get socket manager failed");
mPfd = socketManager.connectSocket(mDevice, mType, mUuid, mPort, getSecurityFlags()); //调用IBluetoothSocketManager 的connectSocket连接Socket
synchronized (this) {
if (DBG) Log.d(TAG, "connect(), SocketState: " + mSocketState + ", mPfd: " + mPfd);
if (mSocketState == SocketState.CLOSED) throw new IOException("socket closed");
if (mPfd == null) throw new IOException("bt socket connect failed");
FileDescriptor fd = mPfd.getFileDescriptor();
mSocket = new LocalSocket(fd);