Browse Source

调整蓝牙逻辑

master
白凤吉 4 months ago
parent
commit
f80e54b83b
  1. 7
      app/src/main/java/com/iflytop/profilometer/MainActivity.java
  2. 67
      app/src/main/java/com/iflytop/profilometer/core/bluetooth/BleManager.java
  3. 2
      app/src/main/java/com/iflytop/profilometer/core/migration/channel/BleDeviceUartChannel.java

7
app/src/main/java/com/iflytop/profilometer/MainActivity.java

@ -2,18 +2,15 @@ package com.iflytop.profilometer;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import androidx.activity.EdgeToEdge;
import androidx.activity.OnBackPressedCallback;
@ -86,7 +83,7 @@ public class MainActivity extends AppCompatActivity {
});
// 初始化 BleManager
bleManager = BleManager.getInstance(this);
bleManager = BleManager.init(this);
bleManager.promptAndEnableBluetooth(this);
// 统一调用权限检查在第一次启动时会请求权限
@ -211,7 +208,7 @@ public class MainActivity extends AppCompatActivity {
}
if (deniedPermissions.isEmpty()) {
// 所有权限均已授予启动 BLE 扫描
BleManager.getInstance(this).startScan();
BleManager.init(this).startScan();
} else {
String message = "以下权限未被授予:"
+ android.text.TextUtils.join("、", deniedPermissions)

67
app/src/main/java/com/iflytop/profilometer/core/bluetooth/BleManager.java

@ -37,10 +37,8 @@ import com.iflytop.profilometer.core.system.SystemService;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@ -82,10 +80,8 @@ public class BleManager {
// 记录设备最后出现时间用于定时清理线程安全
private final Map<BluetoothDevice, Long> deviceLastSeenMap = Collections.synchronizedMap(new HashMap<>());
// 记录已经进行服务查询的设备 MAC 地址为 key避免重复连接线程安全
private final Set<String> processedDevices = Collections.synchronizedSet(new HashSet<>());
// 定时清理 Handler Runnable移除超时设备及清除已处理记录
// 定时清理 Handler Runnable移除超时设备
private final Handler cleanupHandler = new Handler(Looper.getMainLooper());
private final Runnable cleanupRunnable = new Runnable() {
@SuppressLint("MissingPermission")
@ -105,7 +101,6 @@ public class BleManager {
for (BluetoothDevice device : toRemove) {
deviceLastSeenMap.remove(device);
scannedDevices.remove(device);
processedDevices.remove(device.getAddress());
Log.d(TAG, "移除超时设备: " + device.getName() + " - " + device.getAddress());
}
}
@ -129,48 +124,6 @@ public class BleManager {
this.bleDataListener = listener;
}
private class ServiceDiscoveryGattCallback extends BluetoothGattCallback {
private final BluetoothDevice device;
public ServiceDiscoveryGattCallback(BluetoothDevice device) {
this.device = device;
}
@SuppressLint("MissingPermission")
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
Log.d(TAG, "已连接到 " + device.getAddress() + ",开始发现服务");
gatt.discoverServices();
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
Log.d(TAG, "与 " + device.getAddress() + " 断开连接");
gatt.close();
}
}
@SuppressLint("MissingPermission")
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
Log.d(TAG, "在 " + device.getAddress() + " 上发现服务");
BluetoothGattService service = gatt.getService(SERVICE_UUID);
if (service != null) {
// 设备支持目标服务添加到 scannedDevices 列表切换到主线程操作
new Handler(Looper.getMainLooper()).post(() -> {
if (!scannedDevices.contains(device)) {
scannedDevices.add(device);
Log.d(TAG, "设备 " + device.getName() + " 支持目标服务,已添加");
}
});
} else {
Log.d(TAG, "设备 " + device.getAddress() + " 不支持目标服务");
}
}
// 完成服务发现后断开连接
gatt.disconnect();
}
}
/**
* 私有构造函数防止外部直接实例化
*
@ -190,7 +143,7 @@ public class BleManager {
* @param context 上下文
* @return BleManager 实例
*/
public static synchronized BleManager getInstance(Context context) {
public static synchronized BleManager init(Context context) {
if (instance == null) {
instance = new BleManager(context);
}
@ -253,7 +206,7 @@ public class BleManager {
}
/**
* 开始扫描 BLE 设备扫描到的每个设备均依次连接进行服务查询
* 开始扫描 BLE 设备通过设备名称过滤只处理名称以 "SPM" 开头的设备
* 如果扫描到的设备其 MAC 地址与存储的地址一致则自动调用 connectToDeviceSync() 进行连接
*/
@SuppressLint("MissingPermission")
@ -292,7 +245,6 @@ public class BleManager {
// 清空之前的数据
scannedDevices.clear();
deviceLastSeenMap.clear();
processedDevices.clear();
// 定义扫描回调
scanCallback = new ScanCallback() {
@ -326,7 +278,7 @@ public class BleManager {
public void onBatchScanResults(List<ScanResult> results) {
for (ScanResult result : results) {
BluetoothDevice device = result.getDevice();
if (device != null && device.getName() != null) {
if (device != null && device.getName() != null && device.getName().startsWith("SPM")) {
if (result.getScanRecord() != null) {
deviceLastSeenMap.put(device, System.currentTimeMillis());
}
@ -338,14 +290,12 @@ public class BleManager {
stopScan();
connectToDeviceSync(address);
}
processedDevices.add(address);
continue;
}
if (processedDevices.contains(address)) {
continue;
if (!scannedDevices.contains(device)) {
scannedDevices.add(device);
Log.d(TAG, "设备 " + device.getName() + "," + device.getAddress() + " ,已添加至列表 (batch)");
}
processedDevices.add(address);
device.connectGatt(context, USE_AUTO_CONNECT, new ServiceDiscoveryGattCallback(device));
}
}
}
@ -389,7 +339,7 @@ public class BleManager {
}
/**
* 返回当前扫描到的设备列表仅包含支持目标服务的设备
* 返回当前扫描到的设备列表仅包含符合名称条件的设备
*/
public List<BluetoothDevice> getScannedDevices() {
return scannedDevices;
@ -491,7 +441,6 @@ public class BleManager {
}
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
if (NOTIFY_CHARACTERISTIC_UUID.equals(characteristic.getUuid())) {

2
app/src/main/java/com/iflytop/profilometer/core/migration/channel/BleDeviceUartChannel.java

@ -112,7 +112,7 @@ public class BleDeviceUartChannel {
if (reportListener != null) reportListener.onReportReceived(report.packet);
if (deviceOnReportListener != null) dispatchTypedPacket(report.packet);
receiveBuffer.position(offset + report.packet.getPacketLen());
Log.i("BLE","SUC : " + report.packet.getPacketLen());
// Log.i("BLE","SUC : " + report.packet.getPacketLen());
} else if (report.result == TPMIPacketFactory.PacketAnalysisResult.PACKE_NOT_FULLY_RECEIVED) {
// Log.i("BLE","PACKE_NOT_FULLY_RECEIVED : " + data.length);
break;

Loading…
Cancel
Save