简化开发

Android蓝牙(一):设备的扫描

2021-12-10  本文已影响0人  itfitness

目录

效果展示

实现步骤

1.添加权限
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
2.检测蓝牙
 /**
     * 获取蓝牙BluetoothAdapter
     */
    private fun initBluetooth() {
        val bluetoothManager =  getSystemService(BLUETOOTH_SERVICE) as BluetoothManager
        bluetoothAdapter = bluetoothManager.adapter
    }
/**
     * 检测是否支持蓝牙
     */
    private fun checkBluetooth() {
        if(bluetoothAdapter == null){
            ToastUtils.showShort("没有蓝牙")
            return
        }else{
            ToastUtils.showShort("有蓝牙")
            openBluetooth()
        }
    }

假如获取的BluetoothAdapter为null的话说明设备不支持蓝牙

3.开启蓝牙

我们先通过BluetoothAdapter的isEnabled()方法判断蓝牙是否开启

/**
     * 请求打开蓝牙
     */
    private fun openBluetooth() {
        bluetoothAdapter?.let {
            if(!it.isEnabled){
                ToastUtils.showShort("即将开启蓝牙")
                val openBluetoothIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                openBluetoothActivityForResult.launch(openBluetoothIntent)
            }else{
                ToastUtils.showShort("蓝牙以开启")
            }
        }
    }

如果没有开启的话我们需要调用系统的开启蓝牙的Activity,并在onActivityResult中对结果进行处理,这里我们用最新的registerForActivityResult来调用(注意:这里的代码需在上一个方法执行前执行)

/**
     * 注册请求开启蓝牙的Launcher
     */
    private fun registerActivityResultLauncher() {
        openBluetoothActivityForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result->
            if (result.resultCode == RESULT_OK) {
                ToastUtils.showShort("蓝牙开启")
            }else{
                ToastUtils.showShort("未能开启")
            }
        }
    }
4.扫描蓝牙设备

扫描蓝牙需要使用BluetoothAdapter的startDiscovery()方法,并且这里的扫描蓝牙设备需要我们注册广播通过广播来获取扫描的设备

private val bluetoothScanBroadcastReceiver = object :BroadcastReceiver(){
        @SuppressLint("NotifyDataSetChanged")
        override fun onReceive(context: Context?, intent: Intent?) {
            intent?.let {
                when(it.action){
                    //开始扫描
                    BluetoothAdapter.ACTION_DISCOVERY_STARTED->{
                        ToastUtils.showShort("开始扫描")
                        LogUtils.eTag("蓝牙","开始扫描")
                    }
                    //扫描到设备
                    BluetoothDevice.ACTION_FOUND->{
                        it.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)?.let { device->
                            device.name?.let {
                                LogUtils.eTag("蓝牙",device.name)
                            }
                        }
                    }
                    //扫描结束
                    BluetoothAdapter.ACTION_DISCOVERY_FINISHED->{
                        ToastUtils.showShort("扫描结束")
                        LogUtils.eTag("蓝牙",deviceList)
                    }
                    else -> {
                        ToastUtils.showShort("其他")
                        LogUtils.eTag("蓝牙","其他")
                    }
                }
            }
        }
    }
/**
     * 注册扫描蓝牙的广播
     */
    private fun registerBluetoothScan() {
        registerReceiver(bluetoothScanBroadcastReceiver, IntentFilter(BluetoothDevice.ACTION_FOUND))
        registerReceiver(bluetoothScanBroadcastReceiver, IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED))
        registerReceiver(bluetoothScanBroadcastReceiver, IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED))
    }
/**
     * 扫描蓝牙
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun scanBluetooth() {
        bluetoothAdapter?.startDiscovery()
    }

案例源码

完整的代码包括显示扫描的设备列表的逻辑请下载源码查看:https://gitee.com/itfitness/bluetooth-scan-device-demo

上一篇 下一篇

猜你喜欢

热点阅读