在 Android 开辟中,如何实现蓝牙毗连装备?

打印 上一主题 下一主题

主题 924|帖子 924|积分 2772

在 Android 开辟中,实现蓝牙毗连装备通常通过 BluetoothAdapter、BluetoothDevice、BluetoothSocket 等类来实现。你可以利用这些 API 来搜索蓝牙装备、配对装备以及通过蓝牙进行通信。
以下是实现蓝牙毗连装备的具体步调,包含装备扫描、毗连以及数据传输的 Java 代码示例。
1. 添加权限

起首,在 AndroidManifest.xml 中添加须要的权限和蓝牙设置:
  1. <uses-permission android:name="android.permission.BLUETOOTH" />
  2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
  3. <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /> <!-- Android 12 及以上需要 -->
  4. <uses-permission android:name="android.permission.BLUETOOTH_SCAN" /> <!-- Android 12 及以上需要 -->
  5. <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <!-- 扫描设备需要位置权限 -->
  6. <uses-feature android:name="android.hardware.bluetooth" />
  7. <uses-feature android:name="android.hardware.bluetooth_le" android:required="false" />
复制代码
2. 初始化 BluetoothAdapter

BluetoothAdapter 是 Android 蓝牙功能的入口点。通过它可以启用蓝牙、搜索装备、建立毗连等。
  1. BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  2. // 检查设备是否支持蓝牙
  3. if (bluetoothAdapter == null) {
  4.     Log.e("Bluetooth", "设备不支持蓝牙");
  5. } else {
  6.     // 如果蓝牙未打开,请求用户打开蓝牙
  7.     if (!bluetoothAdapter.isEnabled()) {
  8.         Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  9.         startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
  10.     }
  11. }
复制代码
3. 扫描装备

通过 BluetoothAdapter 进行装备扫描,可以找到附近可毗连的蓝牙装备。
  1. // 定义一个 BroadcastReceiver 来处理找到的设备
  2. private final BroadcastReceiver receiver = new BroadcastReceiver() {
  3.     public void onReceive(Context context, Intent intent) {
  4.         String action = intent.getAction();
  5.         if (BluetoothDevice.ACTION_FOUND.equals(action)) {
  6.             // 从 Intent 中获取 BluetoothDevice 对象
  7.             BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
  8.             String deviceName = device.getName();
  9.             String deviceAddress = device.getAddress(); // 设备的 MAC 地址
  10.             Log.d("Bluetooth", "找到设备:" + deviceName + " [" + deviceAddress + "]");
  11.         }
  12.     }
  13. };
  14. // 开始扫描蓝牙设备
  15. IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
  16. registerReceiver(receiver, filter); // 注册 BroadcastReceiver
  17. bluetoothAdapter.startDiscovery(); // 开始扫描
复制代码
在这里,扫描到的装备将通过 BroadcastReceiver 处理,并打印出装备名称和 MAC 地点。
4. 配对装备

在扫描到装备后,利用装备的 MAC 地点来配对和毗连蓝牙装备。
  1. // 假设已经通过扫描获得设备对象 device
  2. BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress); // 使用设备的 MAC 地址获取设备对象
  3. // 检查是否已配对
  4. if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
  5.     // 尝试配对
  6.     device.createBond();
  7. } else {
  8.     Log.d("Bluetooth", "设备已配对");
  9. }
复制代码
5. 建立蓝牙毗连

要与蓝牙装备通信,须要通过 BluetoothSocket 创建毗连。通常利用的是 RFCOMM 协议。
  1. UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // 标准串口服务 UUID
  2. BluetoothSocket bluetoothSocket = null;
  3. try {
  4.     // 创建一个 BluetoothSocket 并连接到设备
  5.     bluetoothSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
  6.     bluetoothSocket.connect(); // 连接设备
  7.     Log.d("Bluetooth", "蓝牙连接成功");
  8. } catch (IOException e) {
  9.     e.printStackTrace();
  10.     Log.e("Bluetooth", "蓝牙连接失败");
  11. }
复制代码
这里的 MY_UUID 是一个标准的串口 UUID,用于创建与装备的毗连。
6. 数据传输

建立毗连后,可以利用输入输出流来进行数据的读写操作。
  1. // 获取输入输出流
  2. InputStream inputStream = null;
  3. OutputStream outputStream = null;
  4. try {
  5.     inputStream = bluetoothSocket.getInputStream();
  6.     outputStream = bluetoothSocket.getOutputStream();
  7. } catch (IOException e) {
  8.     e.printStackTrace();
  9. }
  10. // 发送数据
  11. String message = "Hello from Android!";
  12. try {
  13.     outputStream.write(message.getBytes());
  14.     Log.d("Bluetooth", "数据发送成功");
  15. } catch (IOException e) {
  16.     e.printStackTrace();
  17. }
  18. // 接收数据
  19. byte[] buffer = new byte[1024];
  20. int bytes;
  21. try {
  22.     bytes = inputStream.read(buffer);
  23.     String receivedMessage = new String(buffer, 0, bytes);
  24.     Log.d("Bluetooth", "收到数据: " + receivedMessage);
  25. } catch (IOException e) {
  26.     e.printStackTrace();
  27. }
复制代码
7. 整理和释放资源

在利用完蓝牙后,要关闭 BluetoothSocket 并释放资源。
  1. try {
  2.     if (bluetoothSocket != null) {
  3.         bluetoothSocket.close(); // 关闭连接
  4.     }
  5. } catch (IOException e) {
  6.     e.printStackTrace();
  7. }
复制代码
完整示例代码:
  1. public class BluetoothActivity extends AppCompatActivity {
  2.     private BluetoothAdapter bluetoothAdapter;
  3.     private BluetoothSocket bluetoothSocket;
  4.     private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  5.     private final String deviceAddress = "00:11:22:33:44:55"; // 替换为目标设备的 MAC 地址
  6.     @Override
  7.     protected void onCreate(Bundle savedInstanceState) {
  8.         super.onCreate(savedInstanceState);
  9.         setContentView(R.layout.activity_main);
  10.         bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  11.         
  12.         if (bluetoothAdapter == null) {
  13.             Log.e("Bluetooth", "设备不支持蓝牙");
  14.             return;
  15.         }
  16.         if (!bluetoothAdapter.isEnabled()) {
  17.             Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
  18.             startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
  19.         }
  20.         // 开始扫描设备
  21.         startDeviceDiscovery();
  22.         // 配对设备并连接
  23.         BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
  24.         try {
  25.             bluetoothSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
  26.             bluetoothSocket.connect();
  27.             Log.d("Bluetooth", "蓝牙连接成功");
  28.         } catch (IOException e) {
  29.             e.printStackTrace();
  30.             Log.e("Bluetooth", "蓝牙连接失败");
  31.         }
  32.         // 发送数据
  33.         sendData("Hello from Android!");
  34.         // 接收数据
  35.         receiveData();
  36.     }
  37.     private void startDeviceDiscovery() {
  38.         // 扫描设备的逻辑
  39.     }
  40.     private void sendData(String message) {
  41.         try {
  42.             OutputStream outputStream = bluetoothSocket.getOutputStream();
  43.             outputStream.write(message.getBytes());
  44.             Log.d("Bluetooth", "数据发送成功");
  45.         } catch (IOException e) {
  46.             e.printStackTrace();
  47.         }
  48.     }
  49.     private void receiveData() {
  50.         try {
  51.             InputStream inputStream = bluetoothSocket.getInputStream();
  52.             byte[] buffer = new byte[1024];
  53.             int bytes = inputStream.read(buffer);
  54.             String receivedMessage = new String(buffer, 0, bytes);
  55.             Log.d("Bluetooth", "收到数据: " + receivedMessage);
  56.         } catch (IOException e) {
  57.             e.printStackTrace();
  58.         }
  59.     }
  60. }
复制代码
总结:



  • 蓝牙适配器:通过 BluetoothAdapter 查抄蓝牙状态并进行操作。
  • 装备扫描:通过 BluetoothAdapter.startDiscovery() 和 BroadcastReceiver 监听发现装备。
  • 装备配对:通过 BluetoothDevice.createBond() 实现配对。
  • 毗连装备:通过 BluetoothSocket 建立毗连。
  • 数据传输:通过输入输出流实现数据发送与接收。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

汕尾海湾

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表