蓝牙通信之蓝牙扫描

1.声明蓝牙权限

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

2.获取BluetoothAdapter

private lateinit var bluetoothAdapter: BluetoothAdapter
override fun onStart() {
    super.onStart()
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
}

 3.判断蓝牙是否开启,如果开启则开始扫描,如果未开启则通过动态请求打开蓝牙

if (!bluetoothAdapter.isEnabled) {
    val bIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
    startActivityForResult(bIntent, requestEnable)
} else {
    bluetoothAdapter.startDiscovery()
}
//获取权限后,开始扫描
override fun onRequestPermissionsResult(
    requestCode: Int,
    permissions: Array<out String>,
    grantResults: IntArray
) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    Logger.e("ble--->$requestCode")
    if (requestCode == 1) {
        bluetoothAdapter.startDiscovery()
    }
}

 4.通过广播接收扫描的蓝牙信息

private val mBluetoothReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        val action = intent!!.action
        if (StringUtil.isSameStr(BluetoothDevice.ACTION_FOUND, action)) {
            val device: BluetoothDevice? =
                intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
            if (device != null) {
                scanDeviceList.add(device)
                scanDeviceAdapter.notifyDataSetChanged()
            }
        }
    }

}

5.注册广播监听蓝牙状态,记得在onDestroy注销

val filter = IntentFilter()
//发现设备
filter.addAction(BluetoothDevice.ACTION_FOUND);
//设备连接状态改变
filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
//蓝牙设备状态改变
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBluetoothReceiver, filter)
//取消广播,关闭蓝牙扫描
override fun onDestroy() {
    super.onDestroy()
    bluetoothAdapter.cancelDiscovery()
    unregisterReceiver(mBluetoothReceiver)
}

下篇介绍蓝牙连接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值