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)
scope.cancel()
}
|