Android蓝牙连接demo实现教程

1. 整体流程

下面是实现Android蓝牙连接demo的整体流程,我们将通过以下步骤来完成:

步骤操作
1获取BluetoothAdapter
2打开蓝牙
3搜索蓝牙设备
4连接蓝牙设备
5发送数据
6接收数据

2. 具体步骤

2.1 获取BluetoothAdapter
// 获取BluetoothAdapter
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  • 1.
  • 2.

这段代码用于获取系统默认的BluetoothAdapter,用于管理蓝牙设备的搜索和连接。

2.2 打开蓝牙
if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
  • 1.
  • 2.
  • 3.
  • 4.

这段代码用于检查蓝牙是否已经打开,如果未打开,会弹出系统对话框询问用户是否打开蓝牙。

2.3 搜索蓝牙设备
// 创建BroadcastReceiver对象用于接收蓝牙设备搜索结果
private final BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            // 处理搜索到的蓝牙设备
        }
    }
};

// 注册广播接收器,开始搜索蓝牙设备
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter);
bluetoothAdapter.startDiscovery();
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.

这段代码用于搜索周围的蓝牙设备,并通过BroadcastReceiver接收搜索结果。

2.4 连接蓝牙设备
// 获取要连接的蓝牙设备
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);

// 创建BluetoothSocket用于连接
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID);

// 连接蓝牙设备
socket.connect();
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.

这段代码用于连接指定蓝牙设备,首先根据蓝牙设备的地址获取BluetoothDevice对象,然后创建BluetoothSocket并连接。

2.5 发送数据
// 获取输出流
OutputStream outputStream = socket.getOutputStream();

// 发送数据
String data = "Hello, Bluetooth!";
outputStream.write(data.getBytes());
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

这段代码用于向已连接的蓝牙设备发送数据,首先获取输出流,然后通过输出流发送数据。

2.6 接收数据
// 获取输入流
InputStream inputStream = socket.getInputStream();

// 读取数据
byte[] buffer = new byte[1024];
int bytes;
while ((bytes = inputStream.read(buffer)) != -1) {
    String data = new String(buffer, 0, bytes);
    // 处理接收到的数据
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.

这段代码用于从已连接的蓝牙设备接收数据,首先获取输入流,然后循环读取数据。

结语

通过以上步骤,你已经学会了如何在Android应用中实现蓝牙连接demo。记住,蓝牙连接需要注意权限的申请和线程的使用,希望这篇文章对你有所帮助!如果有任何疑问,欢迎随时向我提问。祝你学习顺利!