最近遇到一个需求,要判断已配对的蓝牙是否打开了互联网访问的开关。 经查看源码,得出以下方法。
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 false
val 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 false
val set: Set<BluetoothDevice> = mBtAdapter.bondedDevices
var device: BluetoothDevice? = null
for (dev in set) {
if (dev.address.equals(strCurBtMac, true)) {
device = dev
break
}
}
if (device == null) {
return false
}
//得到BluetoothDevice的Class对象
val bluetoothDeviceClass: Class<BluetoothDevice> = BluetoothDevice::class.java
try { //得到连接状态的方法
val method: Method = bluetoothDeviceClass.getDeclaredMethod("isConnected")
//打开权限
method.isAccessible = true
return method.invoke(device) as Boolean
} catch (e: Exception) {
e.printStackTrace()
}
return false
}