确定你的手机和助听器都支持蓝牙低功耗(BLE)。
在应用程序中添加以下权限:
在AndroidManifest.xml文件中添加以下服务:
使用BluetoothAdapter启用蓝牙: final BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE); BluetoothAdapter mBluetoothAdapter = bluetoothManager.getAdapter(); if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); }
扫描、连接并发现GATT服务: // 设备的唯一ID private static final UUID HEARING_AID_UUID = UUID.fromString("00000000-0000-0000-0000-000000000000"); // 初始化扫描器 private BluetoothLeScanner mBluetoothLeScanner; // 扫描并连接到助听器 mBluetoothLeScanner.startScan(scanCallback); // GATT连接状态监听器 private final BluetoothGattCallback mGattCallback = new BluetoothGattCallback() { @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { super.onConnectionStateChange(gatt, status, newState); if (newState == BluetoothProfile.STATE_CONNECTED) { // 成功连接到助听器 gatt.discoverServices(); } }
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
// 发现GATT服务
BluetoothGattService service = gatt.getService(HEARING_AID_UUID);
if (