如何进行App蓝牙开发?教程详解!
App蓝牙开发教程
蓝牙技术在物联网和移动应用中扮演着至关重要的角色,本文将详细介绍如何在Android平台上进行蓝牙开发,包括UI界面设计、蓝牙搜索与配对连接以及蓝牙通信的实现,通过本文,你将掌握从基础到高级的蓝牙开发技能,能够独立完成一个蓝牙聊天应用的开发。
一、UI界面设计
1. 布局文件(activity_main.xml)
在app/src/main/res/layout目录下创建或修改布局文件activity_main.xml,使用ConstraintLayout进行界面设计:
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/buttonCheckBluetooth" android:layout_width="0dp" android:layout_height="wrap_content" android:text="是否支持蓝牙" app:layout_constraintEnd_toStartOf="@+id/guideline2" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Button android:id="@+id/buttonBluetoothState" android:layout_width="0dp" android:layout_height="wrap_content" android:text="当前蓝牙状态" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="@+id/guideline2" app:layout_constraintTop_toTopOf="parent" /> <androidx.constraintlayout.widget.Guideline android:id="@+id/guideline2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical" app:layout_constraintGuide_begin="205dp" /> <Button android:id="@+id/buttonTurnOnBluetooth" android:layout_width="0dp" android:layout_height="wrap_content" android:text="打开蓝牙" app:layout_constraintEnd_toStartOf="@+id/guideline2" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/buttonCheckBluetooth" /> <Button android:id="@+id/buttonTurnOffBluetooth" android:layout_width="0dp" android:layout_height="wrap_content" android:text="关闭蓝牙" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="@+id/guideline2" app:layout_constraintTop_toBottomOf="@+id/buttonBluetoothState" /> <Button android:id="@+id/buttonDiscoverable" android:layout_width="0dp" android:layout_height="wrap_content" android:text="使蓝牙可见" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/buttonTurnOnBluetooth" /> <Button android:id="@+id/buttonFindDevices" android:layout_width="0dp" android:layout_height="wrap_content" android:text="搜索设备" app:layout_constraintEnd_toStartOf="@+id/guideline2" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/buttonTurnOffBluetooth" /> <ListView android:id="@+id/listViewDevices" android:layout_width="0dp" android:layout_height="0dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/buttonDiscoverable" app:layout_constraintBottom_toBottomOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>
2. MainActivity.java代码
在MainActivity.java中实现按钮点击事件和列表视图的数据绑定:
package com.example.bluetoothchat; import android.Manifest; import android.bluetooth.BluetoothAdapter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; import java.util.Set; public class MainActivity extends AppCompatActivity { private BluetoothAdapter mBluetoothAdapter; private ArrayAdapter<String> mPairedDevicesArrayAdapter; private ArrayList<String> mDeviceList = new ArrayList<>(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button buttonCheckBluetooth = findViewById(R.id.buttonCheckBluetooth); Button buttonBluetoothState = findViewById(R.id.buttonBluetoothState); Button buttonTurnOnBluetooth = findViewById(R.id.buttonTurnOnBluetooth); Button buttonTurnOffBluetooth = findViewById(R.id.buttonTurnOffBluetooth); Button buttonDiscoverable = findViewById(R.id.buttonDiscoverable); Button buttonFindDevices = findViewById(R.id.buttonFindDevices); ListView listViewDevices = findViewById(R.id.listViewDevices); mPairedDevicesArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, mDeviceList); listViewDevices.setAdapter(mPairedDevicesArrayAdapter); // 检查设备是否支持蓝牙 buttonCheckBluetooth.setOnClickListener(v -> { mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (mBluetoothAdapter == null) { Toast.makeText(this, "当前设备不支持蓝牙功能", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "设备支持蓝牙功能", Toast.LENGTH_SHORT).show(); } }); // 获取当前蓝牙状态 buttonBluetoothState.setOnClickListener(v -> { if (mBluetoothAdapter != null) { if (mBluetoothAdapter.isEnabled()) { Toast.makeText(this, "蓝牙已开启", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "蓝牙已关闭", Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(this, "设备不支持蓝牙功能", Toast.LENGTH_SHORT).show(); } }); // 打开蓝牙 buttonTurnOnBluetooth.setOnClickListener(v -> { if (mBluetoothAdapter != null && !mBluetoothAdapter.isEnabled()) { Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, 1); } }); // 关闭蓝牙 buttonTurnOffBluetooth.setOnClickListener(v -> { if (mBluetoothAdapter != null) { mBluetoothAdapter.disable(); Toast.makeText(this, "蓝牙已关闭", Toast.LENGTH_SHORT).show(); } }); // 使设备可发现 buttonDiscoverable.setOnClickListener(v -> { if (mBluetoothAdapter != null && !mBluetoothAdapter.isDiscovering()) { Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); startActivity(discoverableIntent); Toast.makeText(this, "设备可被发现", Toast.LENGTH_SHORT).show(); } }); // 搜索设备 buttonFindDevices.setOnClickListener(v -> { if (mBluetoothAdapter != null) { mBluetoothAdapter.startDiscovery(); IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); registerReceiver(mReceiver, filter); Toast.makeText(this, "开始搜索设备...", Toast.LENGTH_SHORT).show(); } }); } private final BroadcastReceiver mReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); String deviceName = device.getName() + " " + device.getAddress(); mDeviceList.add(deviceName); mPairedDevicesArrayAdapter.notifyDataSetChanged(); } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { Toast.makeText(context, "搜索结束", Toast.LENGTH_SHORT).show(); unregisterReceiver(this); } } }; }
二、蓝牙搜索与配对连接
1. 添加权限和特性声明(AndroidManifest.xml)
在使用蓝牙功能之前,需要在AndroidManifest.xml中声明相关权限和特性:
<uses-permission android:name="android.permission.BLUETOOTH"/> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
2. Constant.java文件内容如下:
package com.example.wyb.btw3.connect; /** * Created by WYB on 2023/4/24. */ public class Constant { public static final String CONNECTTION_UUID = "00001101-0000-1000-8000-00805F9B34FB"; /** * 开始监听 */ public static final int MSG_START_LISTENING = 1; /** * 结束监听 */ public static final int MSG_FINISH_LISTENING = 2; /** * 有客户端连接 */ public static final int MSG_GOT_A_CLINET = 3; /** * 连接到服务器 */ public static final int MSG_CONNECTED_TO_SERVER = 4; /** * 获取到数据 */ public static final int MSG_GOT_DATA = 5; /** * 出错 */ public static final int MSG_ERROR = -1;}
3. BluetoothController.java文件内容如下:
package com.example.wyb.btw3; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import java.util.ArrayList; import java.util.List; /** * Created by WYB on 2023/4/24. */ public class BlueToothController { private BluetoothAdapter mAdapter; public BlueToothController(){ mAdapter = BluetoothAdapter.getDefaultAdapter(); }/*打开蓝牙设备*/public void turnOnBlueTooth(Activity activity, int requestCode){Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);activity.startActivityForResult(intent, requestCode);}/*查找未绑定的蓝牙设备*/public void findDevice(){assert (mAdapter!=null);mAdapter.startDiscovery();}/*查看已绑定的蓝牙设备*/public List<BluetoothDevice> getBondedDeviceList(){return new ArrayList<>(mAdapter.getBondedDevices());}}```
各位小伙伴们,我刚刚为大家分享了有关“app蓝牙开发教程”的知识,希望对你们有所帮助。如果您还有其他相关问题需要解决,欢迎随时提出哦!
-- 展开阅读全文 --
暂无评论,2人围观