连接流程:
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();//蓝牙适配
判断开启:
if (!mBluetoothAdapter.isEnabled()) { // 未启动 Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); mActivity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); } else { // 已启动,搜索 search(); }
// 启动回调 public boolean onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK) { // 启动后开启搜索 search(); return true; } return false; }
// 启动回调 public boolean onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_OK) { // 启动后开启搜索 search(); return true; } return false; }
连接部分有三种情况:
1、直接连接已知设备:
BluetoothDevice target = mBluetoothAdapter.getRemoteDevice(RemoteDeviceAddr); if (target != null) { bluetoothGatt = target.connectGatt(mActivity, false, bluetoothGattCallback); // BLUETOOTH_NAME = target.getName(); // aniStart(); }
2、选取绑定设备连接:
BluetoothDevice target = null; Set<BluetoothDevice> bondedDevices = mBluetoothAdapter.getBondedDevices(); for (BluetoothDevice bluetoothDevice : bondedDevices) { Log.d("tag.name..",bluetoothDevice.getName()); if (BLUETOOTH_NAME.equalsIgnoreCase(bluetoothDevice.getName())) { target = bluetoothDevice; break; } }
3、搜索新设备:
mBluetoothAdapter.startLeScan(mLeScanCallback);
private final BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) { if (BLUETOOTH_NAME.equalsIgnoreCase(device.getName())) { showDismiss(); isSmart = true; if (bluetoothGatt != null) { bluetoothGatt.disconnect(); bluetoothGatt.close(); bluetoothGatt = null; } bluetoothGatt = device.connectGatt(mActivity, false, bluetoothGattCallback); scanLeDevice(false); } } };
归根结底就是 BluetoothDevice进行connectGatt操作;
遇到的问题:
1、红米Note4X 连接蓝牙模块失败问题:
可能原因:
应该是Android 6.0使用蓝牙需要定位权限。
A、
BLE 连接时对端一定要处于 Advertising 状态,否则是不可能连接成功的。
你的 connect 一定要在BLE onScanResult 中做,确定扫到设备才进行 connect。
B、
每一次连接都会生成一个Gatt对象,每一个Gatt对象都需要断开连接,不然的话,一旦其中有一个Gatt对象没有断开连接,系统就会认为你是在连接的,让你连扫描都扫描不到这个设备,就别说继续连接了
C、
gatt的close和disconnect的区别在于,close除了断开连接外,还会释放掉所有资源,导致不可以直接在后面的操作中用gatt对象的connect直接连接,而disconnect并不释放资源,所以,所有的资源还保存着,就可以用Gatt的connect进行简单恢复连接,而不是在device那一层进行操作。