Android蓝牙学习——搜索、配对、传文件(附源码)

缺乏、安全感 2021-09-14 05:14 464阅读 0赞

导语

蓝牙作为一种成熟、低功耗无线通信技术的先锋,在可穿戴设备领域中扮演着越来越重要的作用。目前流行的蓝牙成功案例在运动手环、行车记录仪、终端解锁、智能家居等领域。接下来,一起动手敲代码吧~

源码下载:http://download.csdn.net/download/csdn_aiyang/9973522

添加权限

  1. <uses-permission android:name="android.permission.BLUETOOTH"/>
  2. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
  3. <uses-permission android:name="android.permission.BLUETOOTH_PRIVILEGED"/>
  4. <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
  5. <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
  6. <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

BluetoothAdapter

获取实例:BluetoothAdapter mBluetoothAdapter = BluetoothAdapter .getDefaultAdapter () ;

  1. if (mBluetoothAdapter == null) {
  2. Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
  3. return;
  4. }

常用方法:

  • isEnabled() 判断系统蓝牙是否打开
  • disable() 无弹窗提示关闭系统蓝牙
  • enable() 无弹窗提示打开系统蓝牙(此操作有点不友好!)
  • startDiscovery() 开始搜索设备 —–适合经典蓝牙和低功耗蓝牙两种
  • cancelDiscovery() 取消搜索设备
  • startLeScan() 开始搜索设备 —–适合扫描低功耗蓝牙,但是在api21以上被标记废弃使用
  • stopLeScan() 停止搜索设备
  • startScan() 开始搜索设备 —–api21以上扫描低功耗蓝牙,通过bluetoothAdapter.getBluetoothLeScanner()方法获取
  • stopScan() 停止搜索设备
  • stopScan() 停止搜索设备

注册广播监听

  1. private IntentFilter makeFilters() {
  2. IntentFilter intentFilter = new IntentFilter();
  3. intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
  4. intentFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
  5. intentFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
  6. intentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_OFF");
  7. intentFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_ON");
  8. intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
  9. intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
  10. return intentFilter;
  11. }
  12. BTBroadcastReceiver receiver = new BTBroadcastReceiver();
  13. registerReceiver(receiver, makeFilters());
  14. receiver.setBRInteractionListener(this);

然后在自定义广播类中进行拦截Action操作,再使用自定义接口与Activity进行交互数据信息显示。(可在源码中查看参考)

发送文本

  1. /** * 蓝牙UUID */ public static UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  2. BluetoothSocket bluetoothSocket =BluetoothDevice.createRfcommSocketToServiceRecord(Comment.SPP_UUID);
  3. OutputStream outputStream =bluetoothSocket.getOutputStream();
  4. outputStream.write(txtString.getBytes("utf-8"));
  5. outputStream.flush();

相关地址下载:

GitHub:https://github.com/aiyangtianci/BluetoothAPP

码云:蓝牙demogiteehttps://gitee.com/AiYangDian/bluetoothdemo

发表评论

表情:
评论列表 (有 0 条评论,464人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Android 学习

    学习缘由 上个礼拜公司要开发个简单的五子棋游戏!其中一个需求就是支持蓝牙对战!所以苦逼的我学习蓝牙方面的知识了! 简介 Bluetooth是目前使用最广泛的

    相关 android 文件

    利用android 传送文件需要解决一下几个问题。 1,发送方选中文件时如何获取文件地址?  以下这段代码作用是返回你选择文件的uri,因此你要重写 onActivityR