Android 5.0 BLE low-power Bluetooth slave device application[Copy link]
Android's low-power Bluetooth applications are very common. Smart bracelets and watches are everywhere, and they basically use BLE communication to exchange data. BLE is basically well supported on both Android and IOS terminal devices, so it has a good development prospect. The various smart devices such as bracelets and watches on the market basically play the role of "slave device". Basically, the smart device completes the Bluetooth broadcast, the mobile phone connects, and then exchanges data. The application of the above method has been supported on Android 4.3 and IOS 7.0 versions, and the application is also relatively wide. There should be many related implementations in the park. You can find them yourself. If you don't want to find them, I will take the time to write another article. Today's main purpose is to say that the broadcast-related API was upgraded in Android 5.0. There are also some instructions in the park, but the reason why I still write this article is that there are few references to data exchange. Since the mobile phone is used for broadcasting, it actually becomes a bracelet, watch, and a slave device. If you want, you can use another mobile phone as the master device so that they can communicate. Okay, let's get into the code... First, apply the permission settings. You still need to add BLE control permissions in AndroidManifest.xml, otherwise you will be annoyed. 1
2 Then we will get to the routine and determine whether the mobile phone supports BLE and whether it supports BLE slave devices. ] 1 if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) { 2 showToast("This device does not support Bluetooth low energy communication"); 3 this.finish(); 4 return; 5 } 6 7 bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE); 8 9 bluetoothAdapter = bluetoothManager.getAdapter(); 10 11 if (bluetoothAdapter == null) { 12 showToast("This device does not support Bluetooth low energy communication"); 13 this.finish(); 14 return; 15 } 16 17 bluetoothLeAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser(); 18 if (bluetoothLeAdvertiser == null) { 19 showToast("This device does not support Bluetooth low energy slave communication"); 20 this.finish(); 21 return; 22 } Copy code I suggest you try it with your debugging device first. Most students are desperate when they get here. You ask me why? You will know after you try it. If you have a face full of what???, then congratulations, your debugging device is the chosen one, let's continue to ride the wind and waves. By the way, tell me what device you use in the comments. Now let's start the whirlwind of broadcasting. Copy code 1 //Broadcast settings 2 AdvertiseSettings.Builder settingBuilder = new AdvertiseSettings.Builder(); 3 settingBuilder.setConnectable(true); 4 settingBuilder.setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_BALANCED); 5 settingBuilder.setTimeout(0); //I have filled in other things, but can't broadcast. //broadcast parameters 11 AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder(); 12 bluetoothAdapter.setName("H8-BlePpl"); //Whatever name you want, it's up to you 13 dataBuilder.setIncludeDeviceName(true); 14 dataBuilder.setIncludeTxPowerLevel(true); 15 16 dataBuilder.addServiceUuid(ParcelUuid.fromString(Const.UUID_SERVICE)); //You can customize the UUID. Check if it is officially defined. 17 AdvertiseData data = dataBuilder.build(); 18 19 bluetoothLeAdvertiser.startAdvertising(settings, data, advertiseCallback); Copy code Then your phone starts broadcasting, saying everyone come connect to me. Don't always search for the address, it seems that the address will change dynamically. It's better to use the name after all, you came up with it. I stupidly checked the Bluetooth MAC address of my phone before, but later found out that it was not the one being broadcast... Broadcast callback I did some work on adding new services. If I didn’t do it, how would you communicate? Copy code 1 private AdvertiseCallback advertiseCallback = new AdvertiseCallback() { 2 @Override 3 public void onStartSuccess(AdvertiseSettings settingsInEffect) { 4 super.onStartSuccess(settingsIn Effect); 5 runOnUiThread(new Runnable() { 6 @Override 7 public void run() { 8 showInfo("1.1 AdvertiseCallback-onStartSuccess"); 9 } 10 }); 11 12 13 bluetoothGattServer = bluetoothManager.openGattServer(getApplicationContext(), 14 bluetoothGattServerCallback); 15 16 BluetoothGattService service = new BluetoothGattService(UUID.fromString( Const.UUID_SERVICE), 17 BluetoothGattService.SERVICE_TYPE_PRIMARY); 18 19 UUID UUID_CHARREAD = UUID.fromString(Const.UUID_CHARACTERISTIC); 20 21 //Characteristic value Read and write settings 22 BluetoothGattCharacteristic characteristicWrite = new BluetoothGattCharacteristic(UUID_CHARREAD, 23 BluetoothGattCharacteristic.PROPERTY_WRITE | 24 BluetoothGattCharacteristic.PROPERTY_READ | 25 BluetoothGattCharacteristic.PROPERTY_NOTIFY, 26 BluetoothGattCharacteristic.PERMIS SION_WRITE); 27 28 UUID UUID_DESCRIPTOR = UUID.fromString(Const.UUID_CHARACTERISTIC_CONFIG); 29 30 BluetoothGattDescriptor descriptor = new BluetoothGattDescriptor(UUID_DESCRIPTOR, BluetoothGattCharacteristic.PERMISSION_WRITE); 31 characteristicWrite.addDescriptor(descriptor); 32 service.addCharacteristic(characteristicWrite); 33 34 bluetoothGattServer.addService(service); 35 3 6 37 runOnUiThread(new Runnable() { 38 @Override 39 public void run() { 40 showInfo("1.2.Service Builded ok"); 41 } 42 }); 43 44 }}; Copy code When you receive the callback of successful broadcast, come on, characteristic value~~We need to communicate anyway~~ You found out that I was lazy and used one characteristic value to read and write. In fact, you can use two if you want. I use NOTIFICATION method to read the master device, you can also use INDICATION method. After the service is established, you will also receive a notification. BLE~~All asynchronous callbacks~~I'm used to it! Copy code 1 private BluetoothGattServerCallback bluetoothGattServerCallback = new BluetoothGattServerCallback() { 2 @Override 3 public void onServiceAdded(int status, BluetoothGattService service) { 4 super.onServiceAdded(status, service); 4] 5 6 final String info = service.getUuid().toString(); 7 runOnUiThread(new Runnable() { 8 @Override 9 public void run() { 10 showInfo("1.3 BluetoothGattServerCallback-onServiceAdded " + info); 11 } 12 }); 13 14 15 } 16 17 @Override 18 public void onConnectionStateChange(BluetoothDevice device, int status, int newState) { 19 super.onConnectionStateChange(device, status, newState); 20 final String info = device.getAddress() + "|" + status + "->" + newState; 21 22 runOnUiThread(new Runnable() { 23 @Override[/ size] 24 public void run() { 25 showInfo("1.4 onConnectionStateChange " + info); 26 } 27 }); 28 } 29 30 @Override [size= 4] 31 public void onCharacteristicReadRequest(BluetoothDevice device, int requestId, int offset, 32 BluetoothGattCharacteristic characteristic) { 33 super.onCharacteristicReadRequest(device, requestId, offset, characteristic); 34 35 36 final String deviceInfo = "Address:" + device.getAddress(); 37 final String info = "Request:" + requestId + "|Offset:" + offset + "|characteristic:" + characteristic.getUuid() + "|Value:" + 38 Util.bytes2HexString(characteristic.getValue());
39
40 runOnUiThread(new Runnable() {
41 @Override
42 public void run() {
43
44 showInfo("=============================================");
45 showInfo("设备信息 " + deviceInfo);
46 showInfo("数据信息 " + info);
47 showInfo("=========onCharacteristicReadRequest=========");
48
49 }
50 });
51
52 bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, characteristic.getValue());
53
54 }
55
56 @Override
57 public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId, BluetoothGattCharacteristic characteristic, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
58 super.onCharacteristicWriteRequest(device, requestId, characteristic,
59 preparedWrite, responseNeeded, offset, value);
60
61 final String deviceInfo = "Name:" + device.getAddress() + "|Address:" + device.getAddress();
62 final String info = "Request:" + requestId + "|Offset:" + offset + "|characteristic:" + characteristic.getUuid() + "|Value:" + Util.bytes2HexString(value);
63
64
65 bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);
66 //TODO:你做数据处理
67
68
69 runOnUiThread(new Runnable() {
70 @Override
71 public void run() {
72
73 showInfo("=============================================");
74 showInfo("设备信息 " + deviceInfo);
75 showInfo("数据信息 " + info);
76 showInfo("=========onCharacteristicWriteRequest=========");
77
78 }
79 });
80
81
82 }
83
84
85 @Override
86 public void onNotificationSent(BluetoothDevice device, int status) {
87 super.onNotificationSent(device,status);
88
89 final String info = "Address:" + device.getAddress() + "|status:" + status;
90
91 runOnUiThread(new Runnable() {
92 @Override
93 public void run() {
94 showInfo("onNotificationSent " + info);
95 }
96 });
97 }
98
99
100 @Override
101 public void onDescriptorWriteRequest(BluetoothDevice device, int requestId, BluetoothGattDescriptor descriptor, boolean preparedWrite, boolean responseNeeded, int offset, byte[] value) {
102 final String deviceInfo = "Name:" + device.getAddress() + "|Address:" + device.getAddress();
103 final String info = "Request:" + requestId + "|Offset:" + offset + "|characteristic:" + descriptor.getUuid() + "|Value:" + Util.bytes2HexString(value);
104
105 runOnUiThread(new Runnable() {
106 @Override
107 public void run() {
108
109 showInfo("=============================================");
110 showInfo("设备信息 " + deviceInfo);
111 showInfo("数据信息 " + info);
112 showInfo("=========onDescriptorWriteRequest=========");
113
114 }
115 });
116
117
118 // 告诉连接设备做好了
119 bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, value);
120 }
121
122 @Override
123 public void onDescriptorReadRequest(BluetoothDevice device, int requestId, int offset, BluetoothGattDescriptor descriptor) {
124
125 super.onDescriptorReadRequest(device, requestId, offset, descriptor);
126
127 final String deviceInfo = "Name:" + device.getAddress() + "|Address:" + device.getAddress();
128 final String info = "Request:" + requestId + "|Offset:" + offset + "|characteristic:" + descriptor.getUuid();
129
130
131 runOnUiThread(new Runnable() {
132 @Override
133 public void run() {
134
135 showInfo("=============================================");
136 showInfo("设备信息 " + deviceInfo);
137 showInfo("数据信息 " + info);
138 showInfo("=========onDescriptorReadRequest=========");
139
140 }
141 });
142
143 // 告诉连接设备做好了
144 bluetoothGattServer.sendResponse(device, requestId, BluetoothGatt.GATT_SUCCESS, offset, null);
145
146
147 }
148
149 };
复制代码
基本上从设备就做完了。