Android之BLE(低功耗)蓝牙开发,价值2000元的学习资源泄露
作者:互联网
// private String uuid_characteristic_send = “自己获取的”;
private boolean isStandByBle;
private boolean isEnableBle;
private Context context;
private Handler handler = new Handler(Looper.getMainLooper());
private final int START_SCAN = 100;
private final int RESET_CONNECT = 101;
// private final UUID[] serviceUuids;
private BleDevice connectedBleDevice;
private BleScanRunnable bleScanRunnable;
private BleResetConnectRunnable bleConnectRunnable;
private BleManager bleManager;
private BleConnectedRunnable bleConnectedRunnable;
private boolean isResetConnect = false;
private boolean isScaning;
private final ReturnTimeOutRunnable returnTimeOutRunnable;
private String currentData = “”;
private final ReceiveDataRunnable receiveDataRunnable;
private BleUtil(Context context) {
this.context = context.getApplicationContext();
bleManager = BleManager.getInstance();
isStandByBle = bleManager.isSupportBle();
isEnableBle = bleManager.isBlueEnable();
// //根据指定的UUID扫描特定的设备
// UUID serviceUuid = UUID.fromString(uuid_service);
// serviceUuids = new UUID[]{serviceUuid};
bleScanRunnable = new BleScanRunnable();
bleConnectRunnable = new BleResetConnectRunnable();
bleConnectedRunnable = new BleConnectedRunnable();
returnTimeOutRunnable = new ReturnTimeOutRunnable();
receiveDataRunnable = new ReceiveDataRunnable();
}
public static BleUtil getInstance(Context context) {
if (bleUtil == null) {
synchronized (BleUtil.class) {
if (bleUtil == null) {
bleUtil = new BleUtil(context);
}
}
}
return bleUtil;
}
public void startBle() {
if (!isStandByBle) {
Toast.makeText(context, “该设备不支持蓝牙功能”, Toast.LENGTH_SHORT).show();
return;
}
bleDevices = new ArrayList<>();
BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
// .setServiceUuids(serviceUuids)
// .setAutoConnect(true)
// .setDeviceMac(“连接到的蓝牙MAC地址”)
.setScanTimeOut(15000)
.build();
bleManager.initScanRule(scanRuleConfig);
if (!bleManager.isBlueEnable()) {
bleManager.enableB
《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享
luetooth();
}
handler.postDelayed(bleScanRunnable, 2 * 100);
}
private void startScan() {
if (isResetConnect && listener != null) {
listener.onResetConnect();
isResetConnect = false;
}
bleManager.scan(new BleScanCallback() {
@Override
public void onScanFinished(List list) {
isScaning = false;
}
@Override
public void onScanStarted(boolean b) {
isScaning = true;
}
@Override
public void onScanning(BleDevice bleDevice) {
Log.e(TAG, bleDevice.getName() + " " + bleDevice.getMac());
bleDevices.add(bleDevice);
if (listener != null) {
listener.onScaningBle(bleDevice);
}
}
});
}
//停止扫描
public void stopScan() {
if (isScaning)
bleManager.cancelScan();
}
//断开连接
public void disConnect() {
handler.removeCallbacks(bleScanRunnable);
handler.removeCallbacks(bleConnectedRunnable);
handler.removeCallbacks(bleConnectRunnable);
handler.removeCallbacks(returnTimeOutRunnable);
handler.removeCallbacks(receiveDataRunnable);
if (connectedBleDevice != null && bleManager.isConnected(connectedBleDevice)) {
stopIndicate();
bleManager.clearCharacterCallback(connectedBleDevice);
bleManager.disconnect(connectedBleDevice);
}
}
//判断是否连接
public boolean isConnected() {
if (connectedBleDevice == null) {
return false;
} else {
return bleManager.isConnected(connectedBleDevice);
}
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void connectBle(BleDevice bleDevice) {
stopScan();
bleManager.connect(bleDevice, new BleGattCallback() {
@Override
public void onStartConnect() {
}
@Override
public void onConnectFail(BleDevice bleDevice, BleException e) {
//连接失败,需做好重连措施
connectedBleDevice = bleDevice;
handler.postDelayed(bleConnectRunnable, 200);
Log.e(“连接失败:”, e.toString());
}
@Override
public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt bluetoothGatt, int i) {
Log.e(TAG, “连接成功”);
receiveData(bleDevice);
connectedBleDevice = bleDevice;
handler.postDelayed(bleConnectedRunnable, 200);
//设备的服务信息及特征信息
// List serviceList = bluetoothGatt.getServices();
// for (BluetoothGattService service : serviceList) {
// UUID uuid_service = service.getUuid();
// Log.e(TAG, "onConnectSuccess:service---- " + uuid_service);
// List characteristicList = service.getCharacteristics();
// for (BluetoothGattCharacteristic characteristic : characteristicList) {
// UUID uuid_chara = characteristic.getUuid();
// Log.e(TAG, “onConnectSuccess: chara” + uuid_chara);
// }
// }
}
@Override
public void onDisConnected(boolean b, BleDevice bleDevice, BluetoothGatt bluetoothGatt, int i) {
//连接断开,需区分异常断开与主动断开(b=true),异常断开的重连操作,需做好时间间隔操作,否者可能导致长时间连接不上的情况
if (b) {
Log.e(TAG, “正常断开”);
bleManager.clearCharacterCallback(bleDevice);
bluetoothGatt.connect();
bleManager.clearCharacterCallback(connectedBleDevice);
if (listener != null) {
listener.onDisConnected();
}
} else {
isResetConnect = true;
Log.e(TAG, “异常断开”);
if (!bleManager.isBlueEnable()) {
bleManager.enableBluetooth();
handler.postDelayed(bleScanRunnable, 200);
} else {
//重连
handler.postDelayed(bleConnectRunnable, 200);
}
}
}
});
}
//连接蓝牙
public void connectBle(String MAC) {
bleManager.connect(MAC, new BleGattCallback() {
@Override
public void onStartConnect() {
}
@Override
public void onConnectFail(BleDevice bleDevice, BleException e) {
//连接失败,需做好重连措施
connectedBleDevice = bleDevice;
handler.postDelayed(bleConnectRunnable, 200);
Log.e(“连接失败:”, e.toString());
}
@Override
public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
Log.e(TAG, “连接成功”);
receiveData(bleDevice);
connectedBleDevice = bleDevice;
handler.postDelayed(bleConnectedRunnable, 200);
}
@Override
public void onDisConnected(boolean b, BleDevice device, BluetoothGatt gatt, int status) {
//连接断开,需区分异常断开与主动断开(b=true),异常断开的重连操作,需做好时间间隔操作,否者可能导致长时间连接不上的情况
if (b) {
Log.e(TAG, “正常断开”);
bleManager.clearCharacterCallback(device);
gatt.connect();
bleManager.clearCharacterCallback(connectedBleDevice);
if (listener != null) {
listener.onDisConnected();
}
} else {
isResetConnect = true;
Log.e(TAG, “异常断开”);
if (!bleManager.isBlueEnable()) {
bleManager.enableBluetooth();
handler.postDelayed(bleScanRunnable, 200);
} else {
//重连
handler.postDelayed(bleConnectRunnable, 200);
}
}
}
});
}
//接受数据
private void receiveData(final BleDevice bleDevice) {
final StringBuilder stringBuilder = new StringBuilder();
bleManager.indicate(bleDevice,
uuid_service,
uuid_characteristic_receive,
new BleIndicateCallback() {
@Override
public void onIndicateSuccess() {
//订阅通知成功
handler.postDelayed(returnTimeOutRunnable, 5 * 1000);
Log.e(TAG, “onIndicateSuccess: 订阅成功”);
}
@Override
public void onIndicateFailure(BleException e) {
Log.e(“接收数据异常------------>”, e.toString());
}
@Override
public void onCharacteristicChanged(byte[] bytes) {
handler.removeCallbacks(returnTimeOutRunnable);
//接收到的数据
String s = BinaryConversionUtils.byte2hex(bytes);
String resultData = BinaryConversionUtils.hexString2String(s);
Pattern pattern = Pattern.compile("\n|\r");
Matcher matcher = pattern.matcher(resultData);
resultData = matcher.replaceAll("");
stringBuilder.append(resultData);
Log.e(“接收数据成功------------>”, stringBuilder.toString());
// Toast.makeText(context, resultData+"–", Toast.LENGTH_SHORT).show();
if (listener != null) {
if (TextUtils.isEmpty(stringBuilder.toString()) || stringBuilder.toString().contains(“ERROR”)) {
//空返回
handler.postDelayed(returnTimeOutRunnable, 200);
} else if (resultData.contains("")) {
//成功返回
currentData = resultData;
handler.postDelayed(receiveDataRunnable, 200);
// stopIndicate();
}
}
}
});
}
//发送数据
// public void sendData(final BleDevice bleDevice, final String str) {
// byte[] data = BinaryConversionUtils.hex2byte(str);
// bleManager.write(bleDevice,
// uuid_service,
// uuid_characteristic_send,
// data,
// true,
// new BleWriteCallback() {
// @Override
// public void onWriteSuccess(int current, int total, byte[] justWrite) {
// // 发送数据到设备成功(分包发送的情况下,可以通过方法中返回的参数可以查看发送进度)
// Log.e(“发送数据成功------------>”, str);
// receiveData(bleDevice);
// bleManager.removeWriteCallback(bleDevice, uuid_characteristic_send);
// }
//
// @Override
// public void onWriteFailure(BleException exception) {
// // 发送数据到设备失败
// Log.e(“发送数据异常------------>”, exception.toString());
// }
// });
// }
public void stopIndicate() {
if (connectedBleDevice != null) {
bleManager.stopIndicate(connectedBleDevice, uuid_service, uuid_characteristic_receive);
bleManager.removeIndicateCallback(connectedBleDevice, uuid_characteristic_receive);
}
}
//扫描设备的实时回调
标签:void,低功耗,bleDevice,private,2000,handler,BLE,bleManager,public 来源: https://blog.csdn.net/m0_64604178/article/details/121972510