蓝牙API笔记

蓝牙API笔记

  • 常用API :

    • BluetoothAdapter
    • BluetoothDevice
    • BluetoothSocket
  • BluetoothAdapter 代表一个蓝牙适配器硬件

  • 通过BluetoothAdapter 可以打开/关闭蓝牙适配器 扫描周边蓝牙设备…

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    
  • 打开/关闭 蓝牙设备

    bluetoothAdapter.enable();  bluetoothAdapter.disable();
    
  • 操作蓝牙设备需要权限

    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
    
  • 扫描/停止扫描蓝牙设备

    bluetoothAdapter.startDiscovery();
    bluetoothAdapter.cancelDiscovery();
    
  • 系统发现周边的蓝牙设备会发一个广播

    BluetoothDevice.ACTION_FOUND
    
  • 监听BluetoothDevice.ACTION_FOUND广播 收到广播后可以从intent中获取到蓝牙设备

  • BluetoothDevice 代表一个可以连接的蓝牙硬件对象
  • 通过BluetoothDevice可以获得 BluetoothSocket对象

    socket = device.createRfcommSocketToServiceRecord(UUID.fromString(
                        "00001101-0000-1000-8000-00805f9b34fb"));
    
  • 获得BluetoothSocket对象之后可以调用 connect();方法跟服务端创建连接
  • 连接创建后可以通过 BluetoothSocket对象获得输入输出流

  • 创建蓝牙连接步骤

    ① 通过BluetoothAdapter打开蓝牙适配器
    ② 通过bluetoothAdapter.startDiscovery();扫描硬件
    ③ 创建广播接收者监听BluetoothDevice.ACTION_FOUND广播 获得BluetoothDevice对象
    ④ 通过device.createRfcommSocketToServiceRecord(UUID uuid);获得BluetoothSocket
    ⑤ BluetoothSocket 的connect();方法 连接到蓝牙设备
    ⑥ 通过BluetoothSocket获得输入输出流 通过流传递数据
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值