网站开发需要学shenme,网站定制牛七科技,西安百度,全国的做网站的公司最近遇到一个需求#xff0c;要判断已配对的蓝牙是否打开了互联网访问的开关。 经查看源码#xff0c;得出以下方法。
1. 首先要判断蓝牙是否打开
2. 已打开的蓝牙是否已配对
3. 验证是否真正打开 /*** 是否打开蓝牙互联网访问*/SuppressLint(MissingPermission要判断已配对的蓝牙是否打开了互联网访问的开关。 经查看源码得出以下方法。
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: SetBluetoothDevice 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: ClassBluetoothDevice BluetoothDevice::class.javatry { //得到连接状态的方法val method: Method bluetoothDeviceClass.getDeclaredMethod(isConnected)//打开权限method.isAccessible truereturn method.invoke(device) as Boolean} catch (e: Exception) {e.printStackTrace()}return false}