文章目录 [隐藏]
1.准备
1)初始化Manager
1 2 3 4 5 6 7 8 |
BluetoothManager bluetoothManager = (BluetoothManager) BluetoothApp.getContext().getSystemService(Context.BLUETOOTH_SERVICE); bluetoothAdapter = bluetoothManager.getAdapter(); if (bluetoothAdapter == null) {//平台不支持 return false; } |
2)判断可用状态
1 2 3 4 5 |
if (!bluetoothAdapter.isEnabled() || BluetoothAdapter.STATE_OFF == bluetoothAdapter.getState()) { return false;//蓝牙未开启 } |
3)开启硬件
1 2 3 4 |
Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBluetoothIntent, CODE_REQUEST_BLUETOOTH);//调用系统页启动蓝牙 |
2.扫描方式1
1)扫描回调
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
private ScanCallback scanCallback = new ScanCallback() { // 扫描结果的回调。每次扫描到一个设备就调用一次(有重复检查回调) @Override public void onScanResult(int callbackType, ScanResult result) { if (result != null) { int rssi = result.getRssi(); // 信号强度 BluetoothDevice device = result.getDevice(); // 设备 String name = device.getName(); // 设备名称 String address = device.getAddress(); // 设备地址,一般为MAC形式xx:xx:xx:xx:xx:xx } } public void onBatchScanResults(List<ScanResult> results) { } public void onScanFailed(int errorCode) { } }; |
2)执行扫描
1 2 3 4 |
BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner(); bluetoothLeScanner.startScan(scanCallback); |
2.扫描方式2
1)广播接收器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
BroadcastReceiver mGattReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (BluetoothLeService.BLEAPI_GATT_FOUNDDEVICE.equals(action)) { BluetoothDevice device = (BluetoothDevice) intent.getExtras().get("device"); if (!TextUtils.isEmpty(device.getName()) && (device.getName().startsWith("UART"))) { mDeviceName = device.getName(); mDeviceAddress = device.getAddress(); mDeviceAddress = mDeviceAddress.replace(":", ""); mDeviceAddress = mDeviceAddress.toLowerCase(); BluetoothConstant.mDeviceAddress = device.getAddress(); String name = mDeviceName + "\n" + mDeviceAddress; if (!deviceMacs.contains(name)) { deviceMacs.add(name); mNewDevicesArrayAdapter.setUseList(cteateDatas(deviceMacs)); mNewDevicesArrayAdapter.notifyDataSetChanged(); } Log.e(TAG, "get device address:=" + mDeviceAddress); } } } }; |
2)广播过滤器
1 2 3 4 |
IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(BluetoothLeService.BLEAPI_GATT_FOUNDDEVICE); |
3)启动广播
1 2 3 |
registerReceiver(mGattReceiver, intentFilter); |
3.连接
1)连接回调-GATT连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
//连接成功或断开,回调此GATT对象 private BluetoothGattCallback gattCallback = new BluetoothGattCallback() { // 连接状态改变时 @Override public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) { Log.e("ard", "连接状态改变:" + status + ",新状态:" + newState + ",GATT:" + gatt.hashCode()); if (status == BluetoothGatt.GATT_SUCCESS) { // 0-gatt连接成功 BluetoothGatt currentBluetoothGatt = gatt; } else { // 失败或断开 } } // 获取到蓝牙设备的服务时 @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { Log.e("ard", "服务开放者状态:" + status + ",GATT:" + gatt.hashCode()); } // 服务中的某个特征码改变时 @Override public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) { Log.e("ard", "特征码改变"); } // 更新特征码时 @Override public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { Log.e("ard", "特征码写入"); } // 读取特征码时 @Override public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) { UUID uuid = characteristic.getUuid(); byte[] data = characteristic.getValue(); Log.e("ard", "特征码读取,uuid:" + uuid + ",data:" + Arrays.toString(data)); } // 更新描述时 @Override public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { Log.e("ard", "描述写入"); } // 读取描述时 @Override public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) { super.onDescriptorRead(gatt, descriptor, status); UUID uuid = descriptor.getUuid(); byte[] data = descriptor.getValue(); Log.e("ard", "描述符读取,uuid:" + uuid + ",data:" + Arrays.toString(data)); } }; |
2)连接设备
1 2 3 4 |
device.connectGatt(context, true, gattCallback); // 根据设备name或address,连接设备 bluetoothLeScanner.stopScan(scanCallback); // 根据需要停止扫描 |
3)断开设备
1 2 3 4 |
currentBluetoothGatt.disconnect(); // 断开 currentBluetoothGatt.close(); // 关闭 |
4.获取蓝牙设备提供的服务
1)开放设备的服务
1 2 3 |
currentBluetoothGatt.discoverServices(); // 开放服务 |
2)获取服务列表
执行上一步后,gatt对象回调BluetoothGattCallback中的onServicesDiscovered方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// 获取到设备的服务列表 @Override public void onServicesDiscovered(BluetoothGatt gatt, int status) { Log.e("ard", "服务开放状态:" + status + ",GATT:" + gatt.hashCode()); List<BluetoothGattService> mServiceList = gatt.getServices(); if (mServiceList != null) { Log.i("ard", "开放的服务数量:" + mServiceList.size()); } for (BluetoothGattService service : mServiceList) { List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics(); Log.i("ard", "扫描到服务:" + service.getUuid()); for (BluetoothGattCharacteristic characteristic : characteristics) { Log.i("ard", "特征码uuid:" + characteristic.getUuid()); } } } |
5.读写BluetoothGattCharacteristic
1)读
1 2 3 |
currentBluetoothGatt.readCharacteristic(characteristic); // 读取特征值 |
执行上一步后,gatt对象回调 BluetoothGattCallback 中的 onCharacteristicRead 方法。
2)更新
1 2 3 4 |
characteristic.setValue(value); currentBluetoothGatt.writeCharacteristic(characteristic); // 更新特征值 |
执行上一步后,gatt对象回调 BluetoothGattCallback 中的 onCharacteristicWrite 方法。
3)开启设备的通知功能
ServiceUUID:00000001-0000-1000-8000-00805f9b34fb
CharacteristicUUID:00000003-0000-1000-8000-00805f9b34fb
DescriptorUUID:00002902-0000-1000-8000-00805f9b34fb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
public void onServicesDiscovered(BluetoothGatt gatt, int status) { Log.e("ard", "服务开放者状态:" + status + ",GATT:" + gatt.hashCode()); gattServices = gatt.getServices(); for (int i = 0; i < gattServices.size(); i++) { BluetoothGattService service = gattServices.get(i); UUID uuidService = service.getUuid(); String uuidServiceString = uuidService.toString(); Log.e("ard", "服务:" + uuidServiceString); List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics(); for (int j = 0; j < characteristics.size(); j++) { BluetoothGattCharacteristic characteristic = characteristics.get(j); UUID uuidCharacteristic = characteristic.getUuid(); String uuidCharacteristicString = uuidCharacteristic.toString(); Log.e("ard", "\t特征码:" + uuidCharacteristicString); if (uuidServiceString.startsWith("00000001")) { if (uuidCharacteristicString.startsWith("00000003")) { int charaProp = characteristic.getProperties(); Log.e("ard", "=-=-=-=000000 " + charaProp); if ((charaProp | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) { BluetoothGattDescriptor descriptor = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb")); boolean b = descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE); boolean b1 = currentBluetoothGatt.writeDescriptor(descriptor); currentBluetoothGatt.setCharacteristicNotification(characteristic, true); Log.e("ard", "=-=-=-=000000xx " + charaProp + b + " " + b1); } } } } } } |
当蓝牙设备有交互,BluetoothGattCallback的onCharacteristicChanged方法会响应。
声明
本文由崔维友 威格灵 cuiweiyou vigiles cuiweiyou 原创,转载请注明出处:http://www.gaohaiyan.com/2256.html
承接App定制、企业web站点、办公系统软件 设计开发,外包项目,毕设