android 如何判断已配对的蓝牙是否打开了互联网访问开关

最近遇到一个需求,要判断已配对的蓝牙是否打开了互联网访问的开关。 经查看源码,得出以下方法。

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
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值