当前位置:   article > 正文

HomeActivity.java和activity_home.xml

HomeActivity.java和activity_home.xml

 一、HomeActivity.java

  1. public class HomeActivity extends AppCompatActivity {
  2. private static final String TAG = "Bluetooth";
  3. private BluetoothGatt bluetoothGatt;
  4. private DeviceAdapter mAdapter1;
  5. private TextView textView1;
  6. private ActivityResultLauncher<Intent> activityLauncher;
  7. private final List<DeviceClass> mbondDeviceList = new ArrayList<>();//搜索到的所有已绑定设备保存为列表
  8. // 服务UUID、特征UUID和描述符UUID
  9. private final UUID serviceUUID = UUID.fromString("0000ff01-0000-1000-8000-00805f9b34fb");
  10. private final UUID characteristicUUID = UUID.fromString("0000ff02-0000-1000-8000-00805f9b34fb");
  11. private final UUID descriptorUUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
  12. @SuppressLint("MissingPermission")
  13. @Override
  14. protected void onCreate(Bundle savedInstanceState) {
  15. super.onCreate(savedInstanceState);
  16. // EdgeToEdge.enable(this);
  17. changeActionBar();
  18. setContentView(R.layout.activity_home);
  19. // show_bondDevice();
  20. ImageView imageViewConnect = findViewById(R.id.connect);
  21. imageViewConnect.setOnClickListener(v -> goToNextActivity());
  22. mAdapter1 = new DeviceAdapter(HomeActivity.this, R.layout.device_item, mbondDeviceList);
  23. ListView listView1 = findViewById(R.id.listview1);
  24. listView1.setAdapter(mAdapter1);
  25. mAdapter1.notifyDataSetChanged();
  26. textView1 = findViewById(R.id.textView2);
  27. Button button2 = findViewById(R.id.button2);
  28. button2.setOnClickListener(v -> send_bond());
  29. Button button3 = findViewById(R.id.button3);
  30. button3.setOnClickListener(v -> close_bond());
  31. activityLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
  32. result -> {
  33. Log.v(TAG, ".... ---");
  34. if (result.getResultCode() == Discoverydevice.RESULT_OK) {
  35. // 从 Intent 中获取蓝牙名称
  36. Intent data = result.getData();
  37. if (data != null) {
  38. String bluetoothName = data.getStringExtra("bluetoothName");
  39. String bluetoothAddress = data.getStringExtra("bluetoothAddress");
  40. Log.v(TAG, "....bluetoothName--接收-" + bluetoothName + "------" + bluetoothAddress);
  41. mbondDeviceList.clear();
  42. mbondDeviceList.add(new DeviceClass(bluetoothName, bluetoothAddress));
  43. mAdapter1.notifyDataSetChanged();
  44. textView1.setText("已连接设备");
  45. BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  46. BluetoothDevice device = bluetoothAdapter.getRemoteDevice(bluetoothAddress);
  47. bluetoothGatt = device.connectGatt(this, false, gattCallback);
  48. Log.e(TAG, "device: " + device);
  49. bluetoothGatt.discoverServices();
  50. // 在这里使用蓝牙名称进行进一步处理,例如更新 UI
  51. } else {
  52. // 没有返回数据的情况,您可以在这里处理失败的逻辑
  53. Log.e(TAG, "....连接失败,未返回数据");
  54. }
  55. } else {
  56. // 连接未成功的情况,您可以在这里处理失败的逻辑
  57. Log.e(TAG, "....连接失败");
  58. }
  59. });
  60. ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
  61. Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
  62. v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
  63. return insets;
  64. });
  65. }
  66. private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
  67. @SuppressLint("MissingPermission")
  68. @Override
  69. public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
  70. if (newState == BluetoothProfile.STATE_CONNECTED) {
  71. // 连接成功
  72. bluetoothGatt.discoverServices(); // 发现设备的服务
  73. Log.v(TAG, "连接成功");
  74. // 停止扫描
  75. stopDevice();
  76. String bluetoothName = gatt.getDevice().getName();
  77. String bluetoothAddress = gatt.getDevice().getAddress();
  78. Log.v(TAG, "bluetoothName" + bluetoothName);
  79. if (bluetoothName != null && bluetoothAddress != null) {
  80. Log.v(TAG, " ---" + bluetoothName);
  81. }
  82. } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
  83. // 连接断开
  84. Log.v(TAG, ".连接断开");
  85. }
  86. }
  87. @SuppressLint("MissingPermission")
  88. @Override
  89. public void onServicesDiscovered(BluetoothGatt gatt, int status) {
  90. // 发现服务后,可以设置通知
  91. if (status == BluetoothGatt.GATT_SUCCESS) {
  92. for (BluetoothGattService bluetoothGattService : gatt.getServices()) {
  93. // 我们可以遍历到该蓝牙设备的全部Service对象。然后通过比较Service的UUID,我们可以区分该服务是属于什么业务的
  94. Log.d(TAG, "Service_UUID" + bluetoothGattService.getUuid());
  95. if (serviceUUID.equals(bluetoothGattService.getUuid())) {
  96. for (BluetoothGattCharacteristic characteristic : bluetoothGattService.getCharacteristics()) {
  97. BluetoothGattCharacteristic service = gatt.getService(serviceUUID).getCharacteristic(characteristicUUID);
  98. if (service != null) { // 添加空值检查
  99. gatt.setCharacteristicNotification(service, true);
  100. BluetoothGattDescriptor descriptor = characteristic.getDescriptor(descriptorUUID);
  101. if (descriptor != null) { // 添加空值检查
  102. descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
  103. gatt.writeDescriptor(descriptor);
  104. } else {
  105. Log.e(TAG, "Descriptor not found for characteristic: " + characteristic.getUuid());
  106. }
  107. } else {
  108. Log.e(TAG, "Characteristic not found for UUID: " + characteristicUUID);
  109. }
  110. }
  111. return;//结束循环操作
  112. }
  113. }
  114. } else {
  115. Log.e(TAG, "onServicesDiscovered received: " + status);
  116. }
  117. }
  118. @SuppressLint("MissingPermission")
  119. @Override
  120. public void onDescriptorWrite(BluetoothGatt gatt, BluetoothGattDescriptor descriptor, int status) {
  121. // 描述符写入成功,现在可以读取特征值
  122. if (status == BluetoothGatt.GATT_SUCCESS) {
  123. // 描述符写入成功,现在可以读取特征值
  124. BluetoothGattCharacteristic characteristic = descriptor.getCharacteristic();
  125. gatt.readCharacteristic(characteristic);
  126. Log.v(TAG, " 读取特征值:");
  127. } else {
  128. Log.v(TAG, "Descriptor write error: " + status);
  129. }
  130. }
  131. @Override
  132. public void onCharacteristicRead(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
  133. // 读取特征值成功
  134. // 读取特征值后的处理逻辑
  135. if (status == BluetoothGatt.GATT_SUCCESS) {
  136. // 读取特征值成功
  137. byte[] data = characteristic.getValue();
  138. String dataStr = byteArrayToHexString(data);
  139. Log.v(TAG, " 读取特征值:" + dataStr);
  140. } else {
  141. Log.e(TAG, "Characteristic read error: " + status);
  142. }
  143. }
  144. private String byteArrayToHexString(byte[] bytes) {
  145. StringBuilder sb = new StringBuilder();
  146. for (byte b : bytes) {
  147. sb.append(String.format("%02X", b));
  148. }
  149. return sb.toString();
  150. }
  151. @Override
  152. public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
  153. // 特征值变化通知的处理逻辑
  154. byte[] data = characteristic.getValue();
  155. String dataStr = byteArrayToHexString(data);
  156. Log.v(TAG, " 通知:" + dataStr);
  157. }
  158. @SuppressLint("MissingPermission")
  159. @Override
  160. public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
  161. if (status == BluetoothGatt.GATT_SUCCESS) {
  162. // 特征值写入成功
  163. Log.v(TAG, "特征值写入成功");
  164. // showToast("特征值写入成功");
  165. } else {
  166. Log.v(TAG, "特征值写入error");
  167. }
  168. }
  169. };
  170. // 开启
  171. @SuppressLint("MissingPermission")
  172. private void send_bond() {
  173. Log.v(TAG, "发送信息");
  174. // 检查是否连接成功
  175. if (bluetoothGatt == null) {
  176. Log.v(TAG, "未连接到蓝牙设备");
  177. return;
  178. }
  179. // 获取要发送的数据
  180. // 将字符 'A' 转换为十六进制字符串
  181. String message = "A";
  182. String hexMessage = ToHex.stringToHex(message);
  183. // 将十六进制字符串转换为字节数组
  184. byte[] bytes = ToHex.hexStringToByteArray(hexMessage);
  185. ToHex.byteArrayToHexString(bytes);
  186. // 获取对应的特征
  187. BluetoothGattService service = bluetoothGatt.getService(serviceUUID);
  188. if (service == null) {
  189. Log.v(TAG, "service == null");
  190. return;
  191. }
  192. BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUUID);
  193. if (characteristic == null) {
  194. Log.v(TAG, "characteristic == null");
  195. return;
  196. }
  197. // 设置要发送的数据 将字节数组发送到蓝牙设备
  198. characteristic.setValue(bytes);
  199. // 发送数据
  200. bluetoothGatt.writeCharacteristic(characteristic);
  201. }
  202. // 关闭
  203. @SuppressLint("MissingPermission")
  204. private void close_bond() {
  205. // 检查是否连接成功
  206. if (bluetoothGatt == null) {
  207. Log.v(TAG, "未连接到蓝牙设备");
  208. return;
  209. }
  210. // 获取要发送的数据
  211. // 将字符 'A' 转换为十六进制字符串
  212. String message = "B";
  213. String hexMessage = ToHex.stringToHex(message);
  214. // 将十六进制字符串转换为字节数组
  215. byte[] bytes = ToHex.hexStringToByteArray(hexMessage);
  216. ToHex.byteArrayToHexString(bytes);
  217. // 获取对应的特征
  218. BluetoothGattService service = bluetoothGatt.getService(serviceUUID);
  219. if (service == null) {
  220. Log.v(TAG, "service == null");
  221. return;
  222. }
  223. BluetoothGattCharacteristic characteristic = service.getCharacteristic(characteristicUUID);
  224. if (characteristic == null) {
  225. Log.v(TAG, "characteristic == null");
  226. return;
  227. }
  228. // 设置要发送的数据 将字节数组发送到蓝牙设备
  229. characteristic.setValue(bytes);
  230. // 发送数据
  231. bluetoothGatt.writeCharacteristic(characteristic);
  232. }
  233. // 停止扫描
  234. @SuppressLint("MissingPermission")
  235. public void stopDevice() {
  236. BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  237. if (bluetoothAdapter != null && bluetoothAdapter.isDiscovering()) {
  238. bluetoothAdapter.cancelDiscovery();
  239. Log.d(TAG, "Bluetooth scan stopped");
  240. } else {
  241. Log.d(TAG, "Bluetooth is not currently scanning");
  242. }
  243. }
  244. public void goToNextActivity() {
  245. Intent intent = new Intent(HomeActivity.this, Discoverydevice.class);
  246. activityLauncher.launch(intent);
  247. }
  248. // 设置修改 ActionBar 的标题 背景颜色
  249. public void changeActionBar() {
  250. // 获取 ActionBar 对象
  251. ActionBar actionBar = getSupportActionBar();
  252. // 设置要显示的标题字符串
  253. String title = "TableLayout(表格布局)";
  254. // 调用自定义方法设置 ActionBar
  255. ActivityUtils.setupCustomActionBar(actionBar, this, title, "#A9CAFE");
  256. }
  257. @Override
  258. protected void onDestroy() {
  259. super.onDestroy();
  260. bluetoothGatt = null;
  261. }
  262. }

二、activity_home.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:app="http://schemas.android.com/apk/res-auto"
  4. xmlns:tools="http://schemas.android.com/tools"
  5. android:id="@+id/main"
  6. android:layout_width="match_parent"
  7. android:layout_height="match_parent"
  8. android:orientation="vertical"
  9. tools:context=".HomeActivity"
  10. tools:ignore="Orientation">
  11. <LinearLayout
  12. android:layout_width="match_parent"
  13. android:layout_height="wrap_content">
  14. <FrameLayout
  15. android:layout_width="wrap_content"
  16. android:layout_height="32dp">
  17. <ImageView
  18. android:id="@+id/connect"
  19. android:layout_width="30dp"
  20. android:layout_height="30dp"
  21. android:layout_gravity="center"
  22. android:background="@drawable/close" />
  23. </FrameLayout>
  24. <TextView
  25. android:layout_width="0dp"
  26. android:layout_height="wrap_content"
  27. android:layout_weight="1"
  28. android:gravity="center"
  29. android:text="Bluetooth" />
  30. <FrameLayout
  31. android:layout_width="wrap_content"
  32. android:layout_height="32dp"
  33. android:gravity="center">
  34. <ImageView
  35. android:layout_width="30dp"
  36. android:layout_height="30dp"
  37. android:layout_gravity="center"
  38. android:background="@drawable/disconnect" />
  39. </FrameLayout>
  40. </LinearLayout>
  41. <TextView
  42. android:id="@+id/textView2"
  43. android:layout_width="wrap_content"
  44. android:layout_height="wrap_content"
  45. android:layout_marginTop="20dp"
  46. android:text="未连接设备" />
  47. <ListView
  48. android:id="@+id/listview1"
  49. android:layout_width="match_parent"
  50. android:layout_height="wrap_content"
  51. android:layout_marginTop="20dp"
  52. android:background="@drawable/listview_style1" />
  53. <LinearLayout
  54. android:layout_width="match_parent"
  55. android:layout_height="wrap_content">
  56. <FrameLayout
  57. android:layout_width="wrap_content"
  58. android:layout_height="wrap_content"
  59. android:layout_weight="1">
  60. <android.widget.Button
  61. android:id="@+id/button2"
  62. android:layout_width="wrap_content"
  63. android:layout_height="wrap_content"
  64. android:layout_gravity="center"
  65. android:background="@drawable/button_color"
  66. android:text="开启"
  67. android:textColor="#000000" />
  68. </FrameLayout>
  69. <FrameLayout
  70. android:layout_width="wrap_content"
  71. android:layout_height="wrap_content"
  72. android:layout_weight="1">
  73. <android.widget.Button
  74. android:id="@+id/button3"
  75. android:layout_width="wrap_content"
  76. android:layout_height="wrap_content"
  77. android:background="@drawable/buttom_dis"
  78. android:text="关闭"
  79. android:textColor="#000000" />
  80. </FrameLayout>
  81. </LinearLayout>
  82. </LinearLayout>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/421657
推荐阅读
相关标签
  

闽ICP备14008679号