过程 搜索-配对-连接-通信
目前配对的环节可以省略了
1.搜索:我是传统的蓝牙搜索➕低功耗蓝牙搜索一起使用的
经典蓝牙:调用
mBluetoothAdapter.startDiscovery();
这时我们需要注册一个通知来监听回调
完整代码如下:
/** * 普通设备搜索 */ public void searchDevices() { try { checkNotNull(mOnSearchDeviceListener); if (mBondedList == null) mBondedList = new ArrayList<>(); if (mNewList == null) mNewList = new ArrayList<>(); if (mBluetoothAdapter == null) { mOnSearchDeviceListener.onError(new NullPointerException(Constants.DEVICE_HAS_NOT_BLUETOOTH_MODULE)); return; } if (mReceiver == null) mReceiver = new Receiver(); // ACTION_FOUND IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); context.registerReceiver(mReceiver, filter); // ACTION_DISCOVERY_FINISHED filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); context.registerReceiver(mReceiver, filter); mNeedunRegister = true; mBondedList.clear(); mNewList.clear(); if (mBluetoothAdapter.isDiscovering()) mBluetoothAdapter.cancelDiscovery(); mBluetoothAdapter.startDiscovery(); mOnSearchDeviceListener.onStartDiscovery(); } catch (Exception e) { e.printStackTrace(); } }
/** * 搜索蓝牙广播 */ private class Receiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { try { String action = intent.getAction(); if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) { if (mOnSearchDeviceListener != null) mOnSearchDeviceListener.onStartDiscovery(); } else if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (device.getBondState() == BluetoothDevice.BOND_NONE) { if (paar != null && !paar.containsKey(device.getAddress())) { paar.put(device.ge