在安卓开发中,蓝牙通信主要依赖以下核心类:
权限 | 作用 |
---|---|
BLUETOOTH |
基础蓝牙功能 |
BLUETOOTH_ADMIN |
管理蓝牙(如开启/关闭) |
ACCESS_FINE_LOCATION |
Android 6.0+ 扫描设备需定位权限 |
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE); }
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { // 设备不支持蓝牙 } else if (!bluetoothAdapter.isEnabled()) { // 请求开启蓝牙 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableIntent, REQUEST_ENABLE_BT); }
// 注册广播接收器 IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(receiver, filter); bluetoothAdapter.startDiscovery(); // 广播接收器监听设备发现 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); // 请求配对 device.createBond(); } } };
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices(); for (BluetoothDevice device : pairedDevices) { // 筛选目标设备(如通过名称或MAC地址) }
final BluetoothDevice targetDevice = ...; // 目标设备 final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // 标准串口服务UUID new Thread(() -> { try { BluetoothSocket socket = targetDevice.createRfcommSocketToServiceRecord(uuid); socket.connect(); // 阻塞直到连接成功或超时 // 连接成功后处理输入输出流 } catch (IOException e) { e.printStackTrace(); } }).start();
InputStream inputStream = socket.getInputStream(); OutputStream outputStream = socket.getOutputStream(); // 发送数据 String data = "Hello Bluetooth"; outputStream.write(data.getBytes()); // 接收数据 byte[] buffer = new byte[1024]; int bytes; while ((bytes = inputStream.read(buffer)) != -1) { String received = new String(buffer, 0, bytes); // 处理接收到的数据 }
问题 | 解决方案 |
---|---|
权限被拒 | 确保动态申请ACCESS_FINE_LOCATION 权限 |
连接失败 | 检查UUID是否一致,确保设备可见性 |
主线程阻塞 | 将connect() 和read() 放在子线程 |
设备不兼容 | 测试不同安卓版本和厂商ROM |
连接不稳定 | 增加重试机制,优化信号强度 |
解答:
双方均创建BluetoothSocket
,一方作为服务器(监听连接),另一方作为客户端(主动连接)。
listenUsingRfcommWithServiceRecord("AppService", uuid)
createRfcommSocketToServiceRecord(uuid)
并连接A的MAC地址。解答:
BufferedOutputStream
)减少I/O