BluetoothChat核心类BluetoothChatService,该类用于管理与其他设备的蓝牙连接和设置。该类包含AcceptThread、ConnectedThread、ConnectThread三个线程。AcceptThread用于监听传入的连接。ConnectedThread用于管理与远程设备的连接,处理所有数据的传入与传出。ConnectThread用于连接远程设备。

类图如下:

我的BluetoothChat示例源码阅读笔记-LMLPHP

我的BluetoothChat示例源码阅读笔记-LMLPHP

 //获取设备蓝牙
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//判断蓝牙是否可用,不可以则跳转到系统蓝牙设置界面
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
}
 //设置设备蓝牙可以被其他设备搜索
//SCAN_MODE_CONNECTABLE_DISCOVERABLE  表明该蓝牙设备同时可以扫码其他蓝牙设备,并且可以被其他蓝牙设备扫描到。 private void ensureDiscoverable() { if (mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}

//获取远程蓝牙设备 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

 //使用listenUsingRfcommWithServiceRecord和listenUsingInsecureRfcommWithServiceRecord以服务端的方式创建监听

 public AcceptThread(boolean secure) {
BluetoothServerSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure"; // Create a new listening server socket
try {
if (secure) {
tmp = mAdapter.listenUsingRfcommWithServiceRecord(
NAME_SECURE, MY_UUID_SECURE);
} else {
tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(
NAME_INSECURE, MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e);
}
mmServerSocket = tmp;
}
接受socket连接 BluetoothSocket socket = null;
socket = mmServerSocket.accept();
 //使用createRfcommSocketToServiceRecord和createInsecureRfcommSocketToServiceRecord以客户端的方式创建监听

 public ConnectThread(BluetoothDevice device, boolean secure) {
mmDevice = device;
BluetoothSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure"; // Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
if (secure) {
tmp = device
.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
} else {
tmp = device
.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
mmSocket = tmp;
} //连接到服务端socket
mmSocket.connect();
 //从socket中使用getInputStream和getOutputStream获取输入流和输出流

 public ConnectedThread(BluetoothSocket socket, String socketType) {
Log.d(TAG, "create ConnectedThread: " + socketType);
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null; // Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
} mmInStream = tmpIn;
mmOutStream = tmpOut;
} //使用输入流读取数据
bytes = mmInStream.read(buffer); //使用输出流写入数据
mmOutStream.write(buffer);
05-02 15:30