Android 蓝牙教程

2025年3月17日 | 阅读 3 分钟

蓝牙是一种与其他设备进行无线数据交换的方式。Android 提供了蓝牙 API 来执行多项任务,例如:

  • 扫描蓝牙设备
  • 连接到其他设备并与之传输数据
  • 管理多个连接等。

Android 蓝牙 API

android.bluetooth 包提供了许多接口和类来处理蓝牙,例如:

  • BluetoothAdapter
  • BluetoothDevice
  • BluetoothSocket
  • BluetoothServerSocket
  • BluetoothClass
  • BluetoothProfile
  • BluetoothProfile.ServiceListener
  • BluetoothHeadset
  • BluetoothA2dp
  • BluetoothHealth
  • BluetoothHealthCallback
  • BluetoothHealthAppConfiguration

android-preferences-example

BluetoothAdapter 类

借助 BluetoothAdapter 类,我们可以执行基本任务,例如启动设备发现、查询已配对(绑定)设备列表、创建 BluetoothServerSocket 实例以监听连接请求等。

BluetoothAdapter 类的常量

BluetoothAdapter 类提供了许多常量。其中一些如下:

  • String ACTION_REQUEST_ENABLE
  • String ACTION_REQUEST_DISCOVERABLE
  • String ACTION_DISCOVERY_STARTED
  • String ACTION_DISCOVERY_FINISHED

BluetoothAdapter 类的方法

BluetoothAdapter 类常用的方法如下:

  • static synchronized BluetoothAdapter getDefaultAdapter() 返回 BluetoothAdapter 的实例。
  • boolean enable() 如果蓝牙适配器已禁用,则启用它。
  • boolean isEnabled() 如果蓝牙适配器已启用,则返回 true。
  • boolean disable() 如果蓝牙适配器已启用,则禁用它。
  • String getName() 返回蓝牙适配器的名称。
  • boolean setName(String name) 更改蓝牙名称。
  • int getState() 返回本地蓝牙适配器的当前状态。
  • Set<BluetoothDevice> getBondedDevices() 返回一个已配对(绑定)的 BluetoothDevice 对象集合。
  • boolean startDiscovery() 启动发现过程。

Android 蓝牙示例:以编程方式启用、禁用和使蓝牙可发现

只需几行代码即可启用或禁用蓝牙。

activity_main.xml

从调色板中拖动一个 TextView 和三个按钮,现在 activity_main.xml 文件将如下所示:

文件:activity_main.xml

提供权限

您需要在 AndroidManifest.xml 文件中提供以下权限。

完整的 AndroidManifest.xml 文件代码如下所示:

文件:AndroidManifest.xml

Activity 类

让我们编写代码来启用、禁用和使蓝牙可发现。

文件:MainActivity.java


您需要将其运行在真实设备(例如手机)上才能测试该应用程序。


Android 蓝牙教程的下一主题

android 蓝牙列出已配对设备示例