Android BLE4.0

示例

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/**
* 需求:
* 1. 界面没有任何按钮操控,需要完全自动化实现多个设备的同时连接,数据处理等操作。
* 2. 每台移动设备对应的蓝牙仪器是固定的,扫描到匹配的设备才可以连接,断开连接时需要自动重新连接。
*/
public class MainActivity extends AppCompatActivity {
private List<BluetoothDevice> devicelist = new ArrayList<>();
private BluetoothAdapter bluetoothAdapter;
private static final long SCAN_PERIOD = 10000; //用于设置蓝牙搜索时间
private boolean flag = true;
private List<BluetoothDevice> dList = new ArrayList<>();
private BluetoothGatt bluetoothGatt;
private BluetoothGattCharacteristic controlCharacteristicl, notifyCharacteristic, batteryCharacteristic;
private static final int ACCESS_LOCATION = 1;
Blue a1;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getPermission();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!bluetoothAdapter.isEnabled()) { //第一步 判断是否开启了蓝牙。。没开启则提示打开蓝牙
bluetoothAdapter.enable();
}

BluetoothManager bluetoothManager = (BluetoothManager)getSystemService(BLUETOOTH_SERVICE);
//得到蓝牙的适配器
bluetoothAdapter = bluetoothManager.getAdapter();
init();
}

@SuppressLint("WrongConstant")
private void getPermission() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
int permissionCheck = 0;
permissionCheck = this.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
permissionCheck += this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
this.requestPermissions( // 请求授权
new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION},
ACCESS_LOCATION);// 自定义常量,任意整型
} else {
// 已经获得权限
}
}
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case ACCESS_LOCATION:
if (hasAllPermissionGranted(grantResults)) {
Log.e("TAG", "onRequestPermissionsResult: OK");
} else {
Log.e("TAG", "onRequestPermissionsResult: NOT OK");
}
break;
}
}

private boolean hasAllPermissionGranted(int[] grantResults) {
for (int grantResult : grantResults) {
if (grantResult == PackageManager.PERMISSION_DENIED) {
return false;
}
}
return true;
}


private void init() {
// 初始化仪器类
a1 = new Blue(this, bluetoothGatt, controlCharacteristicl, notifyCharacteristic);
// 读取缓存的蓝牙设备地址
blueReader();
}

Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
// 开启扫描
scaning();
break;
case 2:
// 仪器
forDelect("");
break;
case 8:
//如果开始扫描后,5秒内没有搜索到任何设备。。则重新开始扫描
if (dList.size() == 0) {
LogUtils.e("没有扫描到设备,从新开始扫描");
bluetoothAdapter.stopLeScan(mLeScanCallback);
handler.sendEmptyMessageDelayed(1, 1000);
}
break;
}
}
};

private void forDelect(String str) {
LogUtils.e(devicelist.toString() + "--------------------------------------仪器断开,删除之前");
for (int i = 0; i < devicelist.size(); i++) {
if (devicelist.get(i).getName().equals(str)) {
devicelist.remove(i);
}
}
LogUtils.e(devicelist.toString() + "--------------------------------------仪器断开,删除之后");
handler.sendEmptyMessageDelayed(1, 3500);
dList.clear();
}

public void startScan() {
flag = true;
// handler.sendEmptyMessage(1);
handler.sendEmptyMessageDelayed(1, 1000);
}
@Override
public void onResume() {
super.onResume();
startScan();
}


@Override
public void onDestroy() {
super.onDestroy();
stopScan();
// if (mReceiver != null) {
// mContext.unregisterReceiver(mReceiver);
// mReceiver = null;
// }
flag = false;
a1.onDes();
}

@Override
public void onStop() {
super.onStop();
stopScan();
flag = false;
}
public void stopScan() {
//如果正在扫描,,就停止扫描
// boolean discovering = bluetoothAdapter.isDiscovering();
// LogUtils.e("是否正在扫描当中;" + discovering);
// if (!discovering) {
bluetoothAdapter.stopLeScan(mLeScanCallback);
LogUtils.e("停止扫描");
// }
// if (discovering) {
// bluetoothAdapter.cancelDiscovery();
// LogUtils.e("停止扫描");
// }
}

public void scaning() {
if (flag) {
LogUtils.e("开始扫描");
//最好调用这个过时的方法,因为可以支持很多API
boolean a = bluetoothAdapter.startLeScan(mLeScanCallback);
LogUtils.e(a + "------------------------------是否成功开启扫描");
if (a)
handler.sendEmptyMessageDelayed(8, 8000);
// else {
// bluetoothAdapter.stopLeScan(mLeScanCallback);
// handler.sendEmptyMessageDelayed(1, 1000);
// }


// bluetoothAdapter.startDiscovery(); //开启扫描
// LogUtils.e(devicelist.size()+"--size");
// if (devicelist .size()!= 0) {
// LogUtils.e(devicelist.toString()+"-------------蓝牙集合");
// handler.sendEmptyMessage(2);
// }
// handler.sendEmptyMessageDelayed(1, 5000);
}
}
public void connecting(BluetoothDevice device) {
// 连接前停止搜索
bluetoothAdapter.stopLeScan(mLeScanCallback);
// bluetoothAdapter.cancelDiscovery();
if (flag) {
LogUtils.e("正在连接");
String name = device.getName();
LogUtils.e(name + "----name->1");
if (name.equals(startWith[0])) {
a1.init(device);
}

LogUtils.e("走完连接方法,重新开始扫描");
handler.sendEmptyMessageDelayed(1, 2000);
}
}
// 设备名
String[] startWith = {""};

private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
if (!(dList.contains(device))) {
Log.e("TAG", device.getName() + "-------------- device.getName()");
Log.e("TAG", device.getAddress() + "--------------device.getAddress()");
dList.add(device);

//项目的正式方法,根据唯一的设备地址判别
if (adress != null && adress.length != 0) {
for (int i = 0; i < adress.length; i++) {
if (device.getName() != null) {
if (adress[i] != null) {
//如果已扫描的设备在本地有记录,并且集合不包含。。。
//则添加到集合中,并且调用连接方法
if (device.getAddress().equals(adress[i]) && !(devicelist.contains(device))) {
devicelist.add(device);
connecting(device);
// handler.sendEmptyMessage(2);
return;
}
}
}
}
}
}
}
};



//这个数组是用来保存地址的,主要用来做判断
private String[] adress;


//文件流。。。读取内存的蓝牙地址
public void blueReader() {

// FileInputStream对文件进行读取
File file = new File("/storage/emulated/0/BlueAdress.txt");
// 打开流
FileInputStream fis = null;
try {

fis = new FileInputStream(file);
byte[] buf = new byte[1024];
int len = fis.read(buf); // 长度 0, 65
String str = new String(buf, 0, len);
StringTokenizer tokener = new StringTokenizer(str, ".");
String[] result = new String[tokener.countTokens()];
adress = new String[tokener.countTokens()];
int i = 0;
while (tokener.hasMoreTokens()) {
result[i++] = tokener.nextToken();
}
for (int a = 0; a < result.length; a++) {
String[] s1 = result[a].split(",");
if (s1[0].equals("")) { // 仪器
adress[a] = s1[1];
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

}

蓝牙设备类,发送指令,接收数据。

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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
public class Blue {
Context mContext;
BluetoothGatt bluetoothGatt;
BluetoothDevice device;
BluetoothGattCharacteristic controlCharacteristicl, notifyCharacteristic;
// 数据处理
BlueCount blueCount;
String uuidFa;
String uuidShou;
String s;
boolean isConnecting = false;
// 工具类
ConversionUtils conversionUtils;

public Blue(final Context mContext, BluetoothGatt bluetoothGatt, final BluetoothGattCharacteristic controlCharacteristicl, BluetoothGattCharacteristic notifyCharacteristic) {
this.mContext = mContext;
this.bluetoothGatt = bluetoothGatt;
this.controlCharacteristicl = controlCharacteristicl;
this.notifyCharacteristic = notifyCharacteristic;
}


// 回调监听
private static OnErWenListener onErWenListener;

public interface OnErWenListener {
void onErWenListener(int position);
}

public void setOnErWenListener(OnErWenListener onErWenListener) {
this.onErWenListener = onErWenListener;
}

public void onDes() {
if (isConnecting) { //如果未连接。
bluetoothGatt.disconnect();
LogUtils.e("耳温仪已断开蓝牙连接");
}
}

public void init(final BluetoothDevice device) {
// y = 1;
onErWenListener.onErWenListener(1);
this.device = device;
conversionUtils = new ConversionUtils();
new Thread() {
@Override
public void run() {
super.run();
if (device == null) {
return;
}
bluetoothGatt = device.connectGatt(mContext, false, gattCallback);
if (bluetoothGatt == null) {
return;
}
uuidShou = "";
uuidFa = "";
}
}.start();
}

private Handler handler1 = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (isConnecting) {
LogUtils.e("-----》发送指令;");
byte[] byte2 = conversionUtils.hexStringToBytes("");//APP给蓝牙设备发送指令
controlCharacteristicl.setValue(byte2);
bluetoothGatt.writeCharacteristic(controlCharacteristicl);
// handler1.sendEmptyMessageDelayed(1, 4000);
}
}
};


//连接4.0蓝牙的回调接口
private BluetoothGattCallback gattCallback = new BluetoothGattCallback() {

/**
* 连接状态改变的回调
*
* @param gatt
* @param status
* @param newState
*/
@Override
public void onConnectionStateChange(final BluetoothGatt gatt, int status, final int newState) {
super.onConnectionStateChange(gatt, status, newState);
//更新UI必须用在主线程
switch (newState) {
case BluetoothGatt.STATE_CONNECTED:
LogUtils.e("连接状态:已连接");
isConnecting = true;
onErWenListener.onErWenListener(2);
//当连接成果以后,开启这个服务,就可以通信了
bluetoothGatt.discoverServices();
break;
case BluetoothGatt.STATE_CONNECTING:
LogUtils.e("连接状态:正在连接");
break;
case BluetoothGatt.STATE_DISCONNECTED:
LogUtils.e("连接状态:断开连接");
bluetoothGatt.close();
onErWenListener.onErWenListener(3);
isConnecting = false;
break;
case BluetoothGatt.STATE_DISCONNECTING:
LogUtils.e("连接状态:正在断开连接");
onErWenListener.onErWenListener(10); //无效,不会走这个方法
break;
default:
break;
}
}

@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
super.onServicesDiscovered(gatt, status);
if (status == BluetoothGatt.GATT_SUCCESS) {
List<BluetoothGattService> services = bluetoothGatt.getServices();
for (BluetoothGattService bluetoothGattService : services) {
// Log.e("====================》", " server:" + bluetoothGattService.getUuid().toString());
List<BluetoothGattCharacteristic> characteristics = bluetoothGattService.getCharacteristics();
for (BluetoothGattCharacteristic bluetoothGattCharacteristic : characteristics) {
// Log.e("====================》", " charac:" + bluetoothGattCharacteristic.getUuid().toString());
// int permission = bluetoothGattCharacteristic.getPermissions();
// LogUtils.e("---->char permission:" + Utils.getCharPermission(permission));
// int property = bluetoothGattCharacteristic.getProperties();
// LogUtils.e("---->char property:" + Utils.getCharPropertie(property));

// 这个UUID要根据蓝牙设备来定 APP---》蓝牙设备
// LogUtils.e(uuidFa + "----1");
if (bluetoothGattCharacteristic.getUuid().toString().equals(uuidFa)) {
// LogUtils.e(uuidFa + "----2");
LogUtils.e("准备发送指令");
controlCharacteristicl = bluetoothGattCharacteristic;
handler1.sendEmptyMessageDelayed(1, 1000);
// handler.sendEmptyMessage(3);
// 蓝牙设备---》APP
// LogUtils.e(uuidShou + "----1");
} else if (bluetoothGattCharacteristic.getUuid().toString().equals(uuidShou)) {
// LogUtils.e(uuidShou + "----2");
LogUtils.e("准备接收数据");
bluetoothGatt.setCharacteristicNotification(bluetoothGattCharacteristic, true);
notifyCharacteristic = bluetoothGattCharacteristic;
//enableNotification(true, notifyCharacteristic);必须执行,不执行的话,APP无法从蓝牙设备获得数据
enableNotification(true, notifyCharacteristic);
}
}
}
}
}

@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicRead(gatt, characteristic, status);
if (status == BluetoothGatt.GATT_SUCCESS)
LogUtils.e("onCharRead " + gatt.getDevice().getName()
+ " read "
+ characteristic.getUuid().toString()
+ " -> "
+ Utils.bytesToHexString(characteristic.getValue()));
}

@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
super.onCharacteristicWrite(gatt, characteristic, status);
ConversionUtils conversionUtils = new ConversionUtils();
LogUtils.e("onCharWrite " + gatt.getDevice().getName()
+ " write "
+ characteristic.getUuid().toString()
+ " -> "
+ conversionUtils.Bytes2HexString(characteristic.getValue()));
}

/**
* 这个方法用于APP接收蓝牙设备发送的数据
*
* @param gatt
* @param characteristic
*/

@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
super.onCharacteristicChanged(gatt, characteristic);
// LogUtils.e("APP准备接收数据");
if (characteristic.getUuid().toString().equals(notifyCharacteristic.getUuid().toString())) {
// if (doi) {
// byte[] value = characteristic.getValue();
// String str = conversionUtils.Bytes2HexString(value);
// String str1 = str.substring(10, 12);
// if (str1.equals("65")) {
// doi = false;
// erWen(characteristic);
// }
// }
erWen(characteristic);
}
}

@Override
public void onDescriptorRead(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorRead(gatt, descriptor, status);
}

@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
super.onDescriptorWrite(gatt, descriptor, status);
}

@Override
public void onReliableWriteCompleted(BluetoothGatt gatt, int status) {
super.onReliableWriteCompleted(gatt, status);
}

@Override
public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
super.onReadRemoteRssi(gatt, rssi, status);
}

@Override
public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
super.onMtuChanged(gatt, mtu, status);
}

@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}

@Override
public boolean equals(Object o) {
return super.equals(o);
}

@Override
protected void finalize() throws Throwable {
super.finalize();
}

@Override
public int hashCode() {
return super.hashCode();
}

@Override
public String toString() {
return super.toString();
}
};

private boolean enableNotification(boolean enable, BluetoothGattCharacteristic characteristic) {
if (bluetoothGatt == null || characteristic == null)
return false;
if (!bluetoothGatt.setCharacteristicNotification(characteristic, enable))
return false;
BluetoothGattDescriptor clientConfig = characteristic.getDescriptor(UUID.fromString("00002902-0000-1000-8000-00805f9b34fb"));
if (clientConfig == null)
return false;
if (enable) {
clientConfig.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
} else {
clientConfig.setValue(BluetoothGattDescriptor.DISABLE_NOTIFICATION_VALUE);
}
LogUtils.e(bluetoothGatt.writeDescriptor(clientConfig) + "---------->>>>>>>>>bluetoothGatt.writeDescriptor(clientConfig)");
return bluetoothGatt.writeDescriptor(clientConfig);
}

double wen;

public double wen() {
return wen;
}

// 数据处理
public void erWen(BluetoothGattCharacteristic characteristic) {
blueCount = new BlueCount();
byte[] value = characteristic.getValue();
String str = conversionUtils.Bytes2HexString(value);
Log.e("接收到的16进制字符串--->>", str);
if (str.equals("")){
if (isConnecting) { //如果未连接。
bluetoothGatt.disconnect();
LogUtils.e("耳温仪已断开蓝牙连接");
return;
}
}
String str1 = str.substring(10, 12);
Log.e("截取后的字符串--->>", str1);
if (str1.equals("")) {
String str2 = str.substring(12, 16);
Log.e("拿到的数据--->>", str2);
blueCount.show(str2);
}else {
// handler1.sendEmptyMessageDelayed(1, 4000);
// return;
}

final double n = blueCount.getM();
// LogUtils.e("开始下一次的延迟发送");
// handler.sendEmptyMessageDelayed(1, 500);

if (n != 0.0) {

}
}
}

数据处理

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
public class BlueCount {

BluetoothGattCharacteristic characteristic;
ConversionUtils conversionUtils;
private double m;

public double getM() {
return m;
}

public BlueCount() {
init();
this.characteristic = characteristic;
}

private final void init() {
conversionUtils = new ConversionUtils();
}


public final void show(String str) {
String s1 = str.substring(0, 2);
// Log.e("第一字节十六进制数值--->>", s1);
int s11 = conversionUtils.LiuZhuanShi(s1);
// Log.e("第一字节十进制数值--->>", s11 + "");
String s2 = str.substring(2, 4);
// Log.e("第二字节十六进制数值--->>", s2);
int s22 = conversionUtils.LiuZhuanShi(s2);
// Log.e("第二字节十进制数值--->>", s22 + "");


m = (double) (s11 + s22 * 256) / (double) 10;

Log.e("测量结果--->>", m + "");
}

}
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
public class ConversionUtils {

public final String hexStr = "0123456789ABCDEF";
public final String[] binaryArray =
{"0000", "0001", "0010", "0011",
"0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011",
"1100", "1101", "1110", "1111"};

/**
* @param hexString
* @return 将十六进制转换为二进制字节数组 16-2
*/
public final byte[] hexStr2BinArr(String hexString) {
//hexString的长度对2取整,作为bytes的长度
int len = hexString.length() / 2;
byte[] bytes = new byte[len];
byte high = 0;//字节高四位
byte low = 0;//字节低四位
for (int i = 0; i < len; i++) {
//右移四位得到高位
high = (byte) ((hexStr.indexOf(hexString.charAt(2 * i))) << 4);
low = (byte) hexStr.indexOf(hexString.charAt(2 * i + 1));
bytes[i] = (byte) (high | low);//高地位做或运算
}
return bytes;
}
//将发送的字符串指令转换为16进制。。。。。用来发送指令
public final byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}

private byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
/**
* @param
* @return 二进制数组转换为二进制字符串 2-2
*/
public final String bytes2BinStr(byte[] bArray) {

String outStr = "";
int pos = 0;
for (byte b : bArray) {
//高四位
pos = (b & 0xF0) >> 4;
outStr += binaryArray[pos];
//低四位
pos = b & 0x0F;
outStr += binaryArray[pos];
}
return outStr;
}

// 从字节数组到十六进制字符串转
public final byte[] hex = "0123456789ABCDEF".getBytes();

public final String Bytes2HexString(byte[] b) {
byte[] buff = new byte[2 * b.length];
for (int i = 0; i < b.length; i++) {
buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
buff[2 * i + 1] = hex[b[i] & 0x0f];
}
return new String(buff);
}

//二进制转换为十进制
public final String con(String str) {
BigInteger src42 = new BigInteger(str, 2);//转换为BigInteger类型
return src42.toString();
}

//十六进制转为十进制
public final int LiuZhuanShi(String str) {
return Integer.parseInt(str, 16);
}

//byte转String
public final String byte2hex(byte[] data) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < data.length; i++) {
String temp = Integer.toHexString(((int) data[i]) & 0xFF);
for (int t = temp.length(); t < 2; t++) {
sb.append("0");
}
sb.append(temp);
}
return sb.toString();
}

}
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
public class LogUtils {
public static final boolean isDebug = true;

public static final void e(String msg) {
if (isDebug)
Log.e("As", "---------->>" + msg);
}

public static final void e(String... msg) {
if (isDebug) {
for (int i = 0; i < msg.length; i++) {
Log.e("MathBox", "------->>" + "msg");
}
}
}

public static final void e(int msg) {
if (isDebug)
Log.e("As", "---------->>" + msg + "");
}

public static final void e(boolean msg) {
if (isDebug)
Log.e("As", "---------->>" + msg + "");
}

public static final void e(Object msg) {
if (isDebug)
Log.e("As", "---------->>" + msg.toString());
}
}

权限:AndroidManifest.xml

1
2
3
4
5
6
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

<!-- Android6.0 蓝牙扫描才需要-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

备注

传送门GitHub