1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > Android BLE 低功耗蓝牙技术使用解析

Android BLE 低功耗蓝牙技术使用解析

时间:2023-08-17 19:39:43

相关推荐

Android BLE 低功耗蓝牙技术使用解析

什么是BLE

BLE 全称为 Bluetooth low energy,意思是低功耗蓝牙。

Android 4.3 (API 18)之后引入Ble.

最常用的Ble蓝牙技术是设备之间传输数据。

Android 使用BLE 技术进行设备通讯

1.首先申请蓝牙相关的权限

<uses-permission android:name="android.permission.BLUETOOTH" /><uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />// android 6.0 之后 蓝牙扫描需要该权限<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

2.开启蓝牙

mBluetoothManager = (BluetoothManager) TestApplication.getInstance().getSystemService(Context.BLUETOOTH_SERVICE);bluetoothAdapter = mBluetoothManager.getAdapter();boolean setName = bluetoothAdapter.setName("xinyu_test" + Build.MODEL);Log.d(TAG, "setName:" + setName);if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);context.startActivityForResult(enableBtIntent, 1);}

3.如果设备本身作为外设,也就是服务端,为其他设备提供数据,那么需要进行广播配置,以及开启服务,服务里面可以监听客户端的读写请求,然后做处理。

// 首先创建一个服务//serviceUUid 是你服务的uuid 一个 BluetoothGattService 可以有多个BluetoothGattCharacteristic 每一个BluetoothGattCharacteristic 负责具体的业务处理BluetoothGattService bluetoothGattService = new BluetoothGattService(UUID.fromString(serviceUUid),BluetoothGattService.SERVICE_TYPE_PRIMARY);//下面是一个可写的BluetoothGattCharacteristicmWriteCharacteristic = new BluetoothGattCharacteristic(UUID.fromString(write), BluetoothGattCharacteristic.PROPERTY_WRITE|BluetoothGattCharacteristic.PROPERTY_NOTIFY, BluetoothGattCharacteristic.PERMISSION_WRITE);bluetoothGattService.addCharacteristic(mWriteCharacteristic);//下面是一个可读的BluetoothGattCharacteristicmNotifyCharacteristic = new BluetoothGattCharacteristic(UUID.fromString(read), BluetoothGattCharacteristic.PROPERTY_READ, BluetoothGattCharacteristic.PERMISSION_READ);bluetoothGattService.addCharacteristic(mNotifyCharacteristic);//创建一个servermBluetoothGattServer = mBluetoothManager.openGattServer(context, new BluetoothGattServerCallback() {@Overridepublic void onConnectionStateChange(BluetoothDevice device, int status, int newState) {super.onConnectionStateChange(device, status, newState);}//客户端有读请求的时候 会走到这里@Overridepublic void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattCharacteristic characteristic) {super.onCharacteristicReadRequest(device, requestId, offset, characteristic);String uuid = characteristic.getUuid().toString();switch (uuid) {case read:// boolean setValue = characteristic.setValue("caoxinyuRead".getBytes());mBluetoothGattServer.sendResponse(device,requestId,0,0,"caoxinyuRead".getBytes());break;}}//客户端有写请求的时候 会走到这里@Overridepublic void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {super.onCharacteristicWriteRequest(device, requestId, characteristic, preparedWrite, responseNeeded, offset, value);String uuid = characteristic.getUuid().toString();switch (uuid) {case write:String msg = new String(value);Log.d("BlueToothBle", msg);// 注意 这里不是主线程 不要弹Toast// Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();// TODO: /6/16 客户端怎么监听呢? 貌似不能用sendResponse 监听不到 需要用notifyCharacteristicChangedbyte[] bytes = (msg + "123").getBytes();boolean sendResponse = mBluetoothGattServer.sendResponse(device, requestId, 0, 0, bytes);Log.d(TAG, "sendResponse:" + sendResponse);Log.d(TAG, "responseNeeded:" + responseNeeded);characteristic.setValue(bytes);mBluetoothGattServer.notifyCharacteristicChanged(device,characteristic,false);break;default:break;}}@Overridepublic void onExecuteWrite(BluetoothDevice device, int requestId, boolean execute) {super.onExecuteWrite(device, requestId, execute);Log.d(TAG, "execute:" + execute);}});//把你的服务添加到server 里面boolean addService = mBluetoothGattServer.addService(bluetoothGattService);List<BluetoothGattService> services = mBluetoothGattServer.getServices();BluetoothGattService service = mBluetoothGattServer.getService(UUID.fromString(serviceUUid));//为什么自己加了service 自己都不能去获取? todo 需要时间 增加服务是异步的 所以启动之后 开始是没有的Log.d(TAG, "addService:" + addService);Log.d(TAG, "services:" + services);//创建设备广播BluetoothLeAdvertiser bluetoothLeAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser();AdvertiseSettings advertiseSettings = new AdvertiseSettings.Builder().setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY).setConnectable(true).setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_HIGH).build();ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[20]);byteBuffer.putShort((short) 220);byteBuffer.put((byte) 0x22);AdvertiseData advertiseData = new AdvertiseData.Builder().//广播的uuid 中心设备去扫描设备的时候 需要传递的参数addServiceUuid(ParcelUuid.fromString(mUuid)).build();AdvertiseData advertiseData1 = new AdvertiseData.Builder().setIncludeDeviceName(false).addManufacturerData(0x038f, new byte[]{(byte) 0x92, (byte) 0x92}).build();//开启广播bluetoothLeAdvertiser.startAdvertising(advertiseSettings, advertiseData, advertiseData1, new AdvertiseCallback() {@Overridepublic void onStartSuccess(AdvertiseSettings settingsInEffect) {super.onStartSuccess(settingsInEffect);Log.d(TAG, "settingsInEffect:" + settingsInEffect);}@Overridepublic void onStartFailure(int errorCode) {super.onStartFailure(errorCode);Log.d(TAG, "errorCode:" + errorCode);}});

4.如果设备作为中心设备,也就是客户端,访问其他蓝牙设备的数据,需要以下代码:

BluetoothAdapter.LeScanCallback callback = new BluetoothAdapter.LeScanCallback() {//扫描到设备会调用这里@Overridepublic void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {Toast.makeText(context, "device:" + device, Toast.LENGTH_SHORT).show();Log.d(TAG, "device:" + device);//停止扫描 必须和开始扫描是同一个callbackbluetoothAdapter.stopLeScan(this);Log.d(TAG, "device:" + device);String deviceName = device.getName();if (deviceName == null) {///questions/26290640/android-bluetoothdevice-getname-return-null//按照这个方法写了 还是返回nullBleAdvertisedData bleAdvertisedData = BleUtil.parseAdertisedData(scanRecord);deviceName = bleAdvertisedData.getName();}Log.d(TAG, TextUtils.isEmpty(deviceName) ? "name is null" : deviceName);//连接到远程蓝牙设备BluetoothGatt bluetoothGatt = device.connectGatt(context, false, new BluetoothGattCallback() {@Overridepublic void onServicesDiscovered(BluetoothGatt gatt, int status) {super.onServicesDiscovered(gatt, status);// TODO: /6/16 这个方法不会回调 只有你调用了 gatt.discoverServices();Log.d(TAG, "status:" + status);List<BluetoothGattService> services = gatt.getServices();Log.d(TAG, "services.size():" + services.size());Log.d(TAG, "gatt:" + gatt);//bluetoothGatt.writeCharacteristic(new BluetoothGattCharacteristic(UUID.fromString(uuid),));//首先根据uuid 拿到服务BluetoothGattService service = gatt.getService(UUID.fromString(serviceUUid));//不能直接拿BluetoothGattCharacteristic 的服务 这样写是拿不到的BluetoothGattService writeservice = gatt.getService(UUID.fromString(write));Log.d(TAG, "service:" + service);Log.d(TAG, "write service:" + writeservice);//根据服务 拿到具体的一个BluetoothGattCharacteristicBluetoothGattCharacteristic characteristic1 = service.getCharacteristic(UUID.fromString(write));boolean setValue = characteristic1.setValue("abc".getBytes());Log.d(TAG, "setValue:" + setValue);gatt.setCharacteristicNotification(characteristic1,true);//写给远程设备boolean writeCharacteristic = gatt.writeCharacteristic(characteristic1);Log.d(TAG, "writeCharacteristic:" + writeCharacteristic);String stringCall = new String(characteristic1.getValue());Log.d(TAG, "stringCall "+stringCall);//读取数据// 注意读写每次只能有一个 /questions/39661417/ble-android-cant-enable-more-than-1-notify-on-read-characteristics/39662793#39662793// BluetoothGattCharacteristic characteristic = service.getCharacteristic(UUID.fromString(read));// Log.d(TAG, "characteristic:read " + characteristic);// boolean readCharacteristic = gatt.readCharacteristic(characteristic);// Log.d(TAG, "readCharacteristic:" + readCharacteristic);}@Overridepublic void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {super.onConnectionStateChange(gatt, status, newState);//连接上之后 去发现远程蓝牙设备的服务gatt.discoverServices();Log.d(TAG, "onConnectionStateChange status:" + status);}@Overridepublic void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {super.onCharacteristicRead(gatt, characteristic, status);Log.d(TAG, "onCharacteristicRead:" + new String(characteristic.getValue()));}@Overridepublic void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {super.onCharacteristicWrite(gatt, characteristic, status);Log.d(TAG, "onCharacteristicWrite:" + new String(characteristic.getValue()));}@Overridepublic void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {super.onCharacteristicChanged(gatt, characteristic);String uuid = characteristic.getUuid().toString();String string = new String(characteristic.getValue());Log.d("BlueToothBle", "onCharacteristicChanged:" + string);}});boolean connect = bluetoothGatt.connect();Log.d(TAG, "bluetoothGatt:" + bluetoothGatt);Log.d(TAG, "connect:" + connect);}};boolean startLeScan = bluetoothAdapter.startLeScan(new UUID[]{UUID.fromString(uuid)}, callback);Toast.makeText(context, "startLeScan:" + startLeScan, Toast.LENGTH_SHORT).show();

参考:

/guide/topics/connectivity/bluetooth-le

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。