邢台做网站优化哪儿好网站推广策划方案
最近遇到一个需求,要判断已配对的蓝牙是否打开了互联网访问的开关。 经查看源码,得出以下方法。
1. 首先要判断蓝牙是否打开
2. 已打开的蓝牙是否已配对
3. 验证是否真正打开
/*** 是否打开蓝牙互联网访问*/@SuppressLint("MissingPermission")fun isOpenBleNet(context: Context, bleMac:String): Boolean {val bluetoothManager: BluetoothManager? = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager?val mBtAdapter = bluetoothManager?.adapter ?: return falseval isOpen= isBleBoundByMac(mBtAdapter,bleMac)return if (isOpen) {//互联网开关是否打开val panState = mBtAdapter.getProfileConnectionState(5)Log.d("TAG", "-----设备已配对,互联网访问状态: ${panState}")panState == BluetoothProfile.STATE_CONNECTED} else {false}}/*** 判断是否已连接配对的蓝牙** @param context* @param strCurBtMac* @return*/@SuppressLint("MissingPermission")fun isBleBoundByMac(mBtAdapter: BluetoothAdapter, strCurBtMac: String?):Boolean {if(!mBtAdapter.isEnabled) return falseval set: Set<BluetoothDevice> = mBtAdapter.bondedDevicesvar device: BluetoothDevice? = nullfor (dev in set) {if (dev.address.equals(strCurBtMac, true)) {device = devbreak}}if (device == null) {return false}//得到BluetoothDevice的Class对象val bluetoothDeviceClass: Class<BluetoothDevice> = BluetoothDevice::class.javatry { //得到连接状态的方法val method: Method = bluetoothDeviceClass.getDeclaredMethod("isConnected")//打开权限method.isAccessible = truereturn method.invoke(device) as Boolean} catch (e: Exception) {e.printStackTrace()}return false}