java
复制代码
public class HomeActivity extends AppCompatActivity {
private static final String TAG = "Bluetooth";
private BluetoothGatt bluetoothGatt;
private DeviceAdapter mAdapter1;
private TextView textView1;
private ActivityResultLauncher<Intent> activityLauncher;
private final List<DeviceClass> mbondDeviceList = new ArrayList<>();//搜索到的所有已绑定设备保存为列表
// 服务UUID、特征UUID和描述符UUID
private final UUID serviceUUID = UUID.fromString("0000ff01-0000-1000-8000-00805f9b34fb");
private final UUID characteristicUUID = UUID.fromString("0000ff02-0000-1000-8000-00805f9b34fb");
private final UUID descriptorUUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
@SuppressLint("MissingPermission")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// EdgeToEdge.enable(this);
changeActionBar();
setContentView(R.layout.activity_home);
// show_bondDevice();
ImageView imageViewConnect = findViewById(R.id.connect);
imageViewConnect.setOnClickListener(v -> goToNextActivity());
mAdapter1 = new DeviceAdapter(HomeActivity.this, R.layout.device_item, mbondDeviceList);
ListView listView1 = findViewById(R.id.listview1);
listView1.setAdapter(mAdapter1);
mAdapter1.notifyDataSetChanged();
textView1 = findViewById(R.id.textView2);
Button button2 = findViewById(R.id.button2);
button2.setOnClickListener(v -> send_bond());
Button button3 = findViewById(R.id.button3);
button3.setOnClickListener(v -> close_bond());
activityLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
result -> {
Log.v(TAG, ".... ---");
if (result.getResultCode() == Discoverydevice.RESULT_OK) {
// 从 Intent 中获取蓝牙名称
Intent data = result.getData();
if (data != null) {
String bluetoothName = data.getStringExtra("bluetoothName");
String bluetoothAddress = data.getStringExtra("bluetoothAddress");
Log.v(TAG, "....bluetoothName--接收-" + bluetoothName + "------" + bluetoothAddress);
mbondDeviceList.clear();
mbondDeviceList.add(new DeviceClass(bluetoothName, bluetoothAddress));
mAdapter1.notifyDataSetChanged();
textView1.setText("已连接设备");
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(bluetoothAddress);
bluetoothGatt = device.connectGatt(this, false, gattCallback);
Log.e(TAG, "device: " + device);
bluetoothGatt.discoverServices();
// 在这里使用蓝牙名称进行进一步处理,例如更新 UI
} else {
// 没有返回数据的情况,您可以在这里处理失败的逻辑
Log.e(TAG, "....连接失败,未返回数据");
}
} else {
// 连接未成功的情况,您可以在这里处理失败的逻辑
Log.e(TAG, "....连接失败");
}
});
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return insets;
});
}
private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
@SuppressLint("MissingPermission")
@Override
public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
if (newState == BluetoothProfile.STATE_CONNECTED) {
// 连接成功
bluetoothGatt.discoverServices(); // 发现设备的服务
Log.v(TAG, "连接成功");
// 停止扫描
stopDevice();
String bluetoothName = gatt.getDevice().getName();
String bluetoothAddress = gatt.getDevice().getAddress();
Log.v(TAG, "bluetoothName" + bluetoothName);
if (bluetoothName != null && bluetoothAddress != null) {
Log.v(TAG, " ---" + bluetoothName);
}
} else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
// 连接断开
Log.v(TAG, ".连接断开");
}
}
@SuppressLint("MissingPermission")
@Override
public void onServicesDiscovered(BluetoothGatt gatt, int status) {
// 发现服务后,可以设置通知
if (status == BluetoothGatt.GATT_SUCCESS) {
for (BluetoothGattService bluetoothGattService : gatt.getServices()) {
// 我们可以遍历到该蓝牙设备的全部Service对象。然后通过比较Service的UUID,我们可以区分该服务是属于什么业务的
Log.d(TAG, "Service_UUID" + bluetoothGattService.getUuid());
if (serviceUUID.equals(bluetoothGattService.getUuid())) {
for (BluetoothGattCharacteristic characteristic : bluetoothGattService.getCharacteristics()) {
BluetoothGattCharacteristic service = gatt.getService(serviceUUID).getCharacteristic(characteristicUUID);
if (service != null) { // 添加空值检查
gatt.setCharacteristicNotification(service, true);
BluetoothGattDescriptor descriptor = characteristic.getDescriptor(descriptorUUID);
if (descriptor != null) { // 添加空值检查
descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
gatt.writeDescriptor(descriptor);
} else {
Log.e(TAG, "Descriptor not found for characteristic: " + characteristic.getUuid());
}
} else {
Log.e(TAG, "Characteristic not found for UUID: " + characteristicUUID);
}
}
return;//结束循环操作
}
}
} else {
Log.e(TAG, "onServicesDiscovered received: " + status);
}
}
@SuppressLint("MissingPermission")
@Override
public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
// 描述符写入成功,现在可以读取特征值
if (status == BluetoothGatt.GATT_SUCCESS) {
// 描述符写入成功,现在可以读取特征值
BluetoothGattCharacteristic characteristic = descriptor.getCharacteristic();
gatt.readCharacteristic(characteristic);
Log.v(TAG, " 读取特征值:");
} else {
Log.v(TAG, "Descriptor write error: " + status);
}
}
@Override
public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
// 读取特征值成功
// 读取特征值后的处理逻辑
if (status == BluetoothGatt.GATT_SUCCESS) {
// 读取特征值成功
byte[] data = characteristic.getValue();
String dataStr = byteArrayToHexString(data);
Log.v(TAG, " 读取特征值:" + dataStr);
} else {
Log.e(TAG, "Characteristic read error: " + status);
}
}
private String byteArrayToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02X", b));
}
return sb.toString();
}
@Override
public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
// 特征值变化通知的处理逻辑
byte[] data = characteristic.getValue();
String dataStr = byteArrayToHexString(data);
Log.v(TAG, " 通知:" + dataStr);
}
@SuppressLint("MissingPermission")
@Override
public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
if (status == BluetoothGatt.GATT_SUCCESS) {
// 特征值写入成功
Log.v(TAG, "特征值写入成功");
// showToast("特征值写入成功");
} else {
Log.v(TAG, "特征值写入error");
}
}
};
// 开启
@SuppressLint("MissingPermission")
private void send_bond() {
Log.v(TAG, "发送信息");
// 检查是否连接成功
if (bluetoothGatt == null) {
Log.v(TAG, "未连接到蓝牙设备");
return;
}
// 获取要发送的数据
// 将字符 'A' 转换为十六进制字符串
String message = "A";
String hexMessage = ToHex.stringToHex(message);
// 将十六进制字符串转换为字节数组
byte[] bytes = ToHex.hexStringToByteArray(hexMessage);
ToHex.byteArrayToHexString(bytes);
// 获取对应的特征
BluetoothGattService service = bluetoothGatt.getService(serviceUUID);
if (service == null) {
Log.v(TAG, "service == null");
return;
}
BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUUID);
if (characteristic == null) {
Log.v(TAG, "characteristic == null");
return;
}
// 设置要发送的数据 将字节数组发送到蓝牙设备
characteristic.setValue(bytes);
// 发送数据
bluetoothGatt.writeCharacteristic(characteristic);
}
// 关闭
@SuppressLint("MissingPermission")
private void close_bond() {
// 检查是否连接成功
if (bluetoothGatt == null) {
Log.v(TAG, "未连接到蓝牙设备");
return;
}
// 获取要发送的数据
// 将字符 'A' 转换为十六进制字符串
String message = "B";
String hexMessage = ToHex.stringToHex(message);
// 将十六进制字符串转换为字节数组
byte[] bytes = ToHex.hexStringToByteArray(hexMessage);
ToHex.byteArrayToHexString(bytes);
// 获取对应的特征
BluetoothGattService service = bluetoothGatt.getService(serviceUUID);
if (service == null) {
Log.v(TAG, "service == null");
return;
}
BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUUID);
if (characteristic == null) {
Log.v(TAG, "characteristic == null");
return;
}
// 设置要发送的数据 将字节数组发送到蓝牙设备
characteristic.setValue(bytes);
// 发送数据
bluetoothGatt.writeCharacteristic(characteristic);
}
// 停止扫描
@SuppressLint("MissingPermission")
public void stopDevice() {
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
Log.d(TAG, "Bluetooth scan stopped");
} else {
Log.d(TAG, "Bluetooth is not currently scanning");
}
}
public void goToNextActivity() {
Intent intent = new Intent(HomeActivity.this, Discoverydevice.class);
activityLauncher.launch(intent);
}
// 设置修改 ActionBar 的标题 背景颜色
public void changeActionBar() {
// 获取 ActionBar 对象
ActionBar actionBar = getSupportActionBar();
// 设置要显示的标题字符串
String title = "TableLayout(表格布局)";
// 调用自定义方法设置 ActionBar
ActivityUtils.setupCustomActionBar(actionBar, this, title, "#A9CAFE");
}
@Override
protected void onDestroy() {
super.onDestroy();
bluetoothGatt = null;
}
}