美文网首页
Android蓝牙SPP通信客户端实现

Android蓝牙SPP通信客户端实现

作者: 会上网的井底之蛙 | 来源:发表于2023-04-23 14:58 被阅读0次

开启权限

AndroidManifest中定义权限

<!-- 扫描蓝牙设备或者操作蓝牙设置 -->
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!-- 使用蓝牙的权限 -->
<uses-permission android:name="android.permission.BLUETOOTH" />

<!--精准定位权限,作用于Android6.0+ -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<!--模糊定位权限,作用于Android6.0+ -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<!--以下三个是Android12中新增,作用于Android12.0+ -->
<!-- Android 12在不申请定位权限时,必须加上android:usesPermissionFlags="neverForLocation",否则搜不到设备 -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" android:usesPermissionFlags="neverForLocation" tools:targetApi="s"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

动态申请权限

private fun initPermission() {
    val permissionList: ArrayList<String> = ArrayList<String>()
    if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.S){
        // Android 版本大于等于 Android12 时
        permissionList.add(Manifest.permission.BLUETOOTH_SCAN)
        permissionList.add(Manifest.permission.BLUETOOTH_ADVERTISE)
        permissionList.add(Manifest.permission.BLUETOOTH_CONNECT)
    } else {
        // Android 版本小于 Android12 及以下版本
        permissionList.add(Manifest.permission.ACCESS_COARSE_LOCATION)
        permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION)
    }
    ActivityCompat.requestPermissions(this,permissionList.toArray(emptyArray()),1000)
}


开启蓝牙

如果蓝牙没有开启,跳转到系统蓝牙设置界面,打开蓝牙:

val bluetoothAdapter =  BluetoothAdapter.getDefaultAdapter()

if (!bluetoothAdapter.isEnabled()) {
    val intent = Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
    context.startActivity(intent)
}

开启蓝牙状态监听

private var adapter: BluetoothTerminalAdapter?=null
private var list:MutableList<BluetoothDevice> = mutableListOf()
private var broadcastReceiver: BluetoothBroadcastReceive?=null

fun registerReceiver() {
    if (broadcastReceiver == null) {
        broadcastReceiver = BluetoothBroadcastReceive()
        val intent = IntentFilter()
        
        intent.addAction(BluetoothDevice.ACTION_FOUND) // 用BroadcastReceiver来取得搜索结果
        intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED)
        intent.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)
        intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED)
        intent.addAction(BluetoothDevice.ACTION_ACL_CONNECTED)
        intent.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED)
        intent.addAction(BluetoothDevice.ACTION_NAME_CHANGED)
        intent.addAction("android.bluetooth.BluetoothAdapter.STATE_OFF")
        intent.addAction("android.bluetooth.BluetoothAdapter.STATE_ON")
        intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED)

        requireContext().registerReceiver(broadcastReceiver, intent)
    }
}

fun stopDiscovery() {
    BluetoothAdapter.getDefaultAdapter().cancelDiscovery()
}

fun onBluetoothConnect(device: BluetoothDevice) {
    //连接成功后的动作,比如更新UI,开始FTP通信等
    ......
}    

fun onBluetoothDisConnect() {
    //连接失败后的动作,比如更新UI,
}

inner class BluetoothBroadcastReceive : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        val action = intent?.action
        val device = intent?.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)

        when (action) {
            BluetoothDevice.ACTION_FOUND -> {
                if (device != null)){
                    if (!list.contains(device)) {
                        list.add(device)
                        adapter?.notifyDataSetChanged()
                    }
                }
            }
            BluetoothAdapter.ACTION_DISCOVERY_FINISHED -> {
                stopDiscovery()
            }
            BluetoothDevice.ACTION_ACL_CONNECTED -> {
                //连接后还需要配对,配对成功才能通信
                if (device != null){
                    adapter?.notifyDataSetChanged()
                }
            }
            BluetoothDevice.ACTION_ACL_DISCONNECTED -> {
                if (device != null){
                    //如果连接失败或者连接成功,但是没有配对,则会调用连接失败
                    onBluetoothDisConnect()
                    adapter?.notifyDataSetChanged()
                }
            }
            BluetoothAdapter.ACTION_STATE_CHANGED -> {
                val blueState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, 0)
                when (blueState) {
                    BluetoothAdapter.STATE_OFF -> {
                        stopDiscovery()
                        onBluetoothDisConnect()
                    }
                }
            }
            BluetoothDevice.ACTION_BOND_STATE_CHANGED -> {
                val state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1)
                when (state) {
                    BluetoothDevice.BOND_NONE -> {adapter?.notifyDataSetChanged()}
                    BluetoothDevice.BOND_BONDED -> {
                        if (device != null){
                            adapter?.notifyDataSetChanged()
                            //配对成功才能通讯,所以只有配对成功才表示真正的连接成功
                            onBluetoothConnect(device)
                        }
                    }
                }
            }
            BluetoothDevice.ACTION_NAME_CHANGED -> {
                for(i in 0 until  list.size) {
                    if (list[i].address == device?.address) {
                        if (device != null) {
                            list[i] = device
                            adapter?.notifyDataSetChanged()
                        }
                        break
                    }
                }
            }
        }
    }
}

开启连接与配对

说明一下,原始的实现方式是在系统蓝牙设置界面进行配对,在广播收到“BluetoothDevice.ACTION_ACL_CONNECTED”后,开始调用“bluetoothDevice.createRfcommSocketToServiceRecord(SPP_UUID)”进行SPP通信,但是此方式对有的蓝牙服务端的程序不启作用,可采用的是另一种方式:
需要进行通信的bluetoothDevice,直接调用createRfcommSocketToServiceRecord函数:

companion object{
    //蓝牙串口服务 (SPP) 的 UUID
    val SPP_UUID: UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")
}
private var bluetoothSocket:BluetoothSocket? = null
private var inputStream: InputStream? = null   // 用来收数据
private var outputStream: OutputStream? = null // 用来发数据

fun startReadyConnect():Boolean {
    //需要在线程中连接,否则超时会引起ANR
    val coroutineScope = CoroutineScope(Dispatchers.IO)
    coroutineScope?.launch {
         //有个工具类BluetoothUtils,里面保存了等待连接的蓝牙设备对象
         var bluetoothDevice = BluetoothUtils.getWaitingForConnectionDevice()
         bluetoothDevice?.let {
            try {
                //通过createRfcommSocketToServiceRecord函数调用,这会引起蓝牙底层的配对连接动作
                //如果连接成功,系统会自动弹出配对对话框,需要用户在一定时间里完成配对
                //如果在一定时间里配对成功,则返回true,否则不配对或者取消配对,都会引起异常
                bluetoothSocket = bluetoothDevice.createRfcommSocketToServiceRecord(SPP_UUID)
                bluetoothSocket?.connect()

                inputStream = bluetoothSocket?.inputStream
                outputStream = bluetoothSocket?.outputStream

                if (inputStream != null && outputStream != null) {
                    BluetoothUtils.waitingForConnectionDevice = null
                    BluetoothUtils.connectedDevice = it
                    return true
                }
            } catch (e:Exception) {
                e.printStackTrace()
            }
        }
        BluetoothUtils.waitingForConnectionDevice = null
        BluetoothUtils.connectedDevice = null
        BluetoothUtils.bluetoothDisConnect()
        return false
    }
}

发送数据

//在子线程里运行,比如先将数据放在LinkedBlockingQueue中,子线程while循环不断从LinkedBlockingQueue中取出数据
//调用writeBytes函数发送出去
fun writeBytes(bytes: ByteArray) {
    if (isRun){
        try {
            outputStream?.write(bytes)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

接收数据

//在子线程中的while循环里运行
fun read(): ByteArray? {
    val num = inputStream?.read(buffer)?:0
    if (num > 0) {
        val readBytes = ByteArray(num)
        System.arraycopy(buffer,0,readBytes,0,num)
        return readBytes
    }
    return null
}

总结

1.Android不同版本,蓝牙权限需要适配,分为6.0之前,6.0至11.0之间、12.0及之后,三类不同版本的适配

2.SPP通信前需要先进行蓝牙配对与连接

3.蓝牙配对操作针对实际情况采用系统蓝牙设置里进行配对或者采用调用Create Socket通信接口自动触发配对

4.有些操作需要在子线程中进行,防止ANR

相关文章

  • 基于 arduino 蓝牙模块

    Arduino蓝牙模块与Android实现通信 http://www.cnblogs.com/rayray/p/3...

  • 学习策略模式-积淀

    最近需要做一个安卓蓝牙spp通信的小项目,由于之前没接触过蓝牙通信技术,对于这一技术,需要花一段时间理解各种原理,...

  • 近场通信 蓝牙

    android应用层开发 近场通信 首选蓝牙 先了解一下:什么是蓝牙? 蓝牙是一种无线技术标准,可实现手机与手机,...

  • 学习笔记_基于Kotlin的蓝牙通信工具类

    使用Kotlin简单实现蓝牙通信 蓝牙通信步骤 获取蓝牙适配器 检查蓝牙是否可用 打开/关闭蓝牙 搜索附近可见蓝牙...

  • 低功耗蓝牙

    前言 前段时间开发智能音乐灯,手机既要传递音频数据又要传递控制数据给蓝牙,SPP、BLE for Android都...

  • Android实践 -- Android蓝牙设置连接

    蓝牙开发相关 使用Android Bluetooth APIs将设备通过蓝牙连接并通信,设置蓝牙,查找蓝牙设备,配...

  • Android 经典蓝牙开发(二)

    本文章经典蓝牙开发目录: 1、权限申请2、开启蓝牙3、扫描蓝牙4、配对蓝牙5、连接蓝牙6、通信(实现双向通信)(我...

  • 蓝牙学习-SPP

    SPP - Serial Port Profifile SPP提供两个连接的蓝牙设备可以建立虚拟串口连接的能力。务...

  • Android 低功耗(BLE)蓝牙(三)

    本文章经典蓝牙开发目录: 1、权限申请2、开启蓝牙3、扫描蓝牙4、连接蓝牙5、通信(实现双向通信)(这个是公司的设...

  • android蓝牙通讯开发---与蓝牙模块进行通信

    转自android蓝牙开发---与蓝牙模块进行通信 近半个月来一直在搞android蓝牙这方面,主要是项目需要与蓝...

网友评论

      本文标题:Android蓝牙SPP通信客户端实现

      本文链接:https://www.haomeiwen.com/subject/fdqyjdtx.html