如何在没有Inernet连接的情况下从wifi禁用自动重新检测?

时间:2019-07-16 16:02:12

标签: android

我想以编程方式通过没有互联网连接的Wi-fi连接到设备。在某些设备上,它运作良好。但是例如 Google像素,连接后,经过一段时间(10-20秒),它会通过互联网连接自动重新连接到Wi-Fi:

fun connectToApplianceWifi(connectivityManager: ConnectivityManager, wifiManager: WifiManager, ssid: String?) {
    wifiManager.configuredNetworks.forEach { confItem: WifiConfiguration ->
        wifiManager.removeNetwork(confItem.networkId)
        wifiManager.saveConfiguration()
    }
    wifiManager.disableNetwork(wifiManager.connectionInfo.networkId)
    val netId: Int
    val existedNetwork = wifiManager.configuredNetworks.firstOrNull { configItem -> configItem.SSID == "\"" + ssid + "\"" }
    if (existedNetwork != null) {
        netId = existedNetwork.networkId
    } else {
        val wifiConfig = WifiConfiguration()
        wifiConfig.SSID = "\"" + ssid + "\""
        wifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
        netId = wifiManager.addNetwork(wifiConfig)
    }
    wifiManager.disconnect()
    wifiManager.enableNetwork(netId, true)
    val reconnectResult = wifiManager.reconnect()
    if (!reconnectResult || netId == -1) {
        setApplianceFailure()
    }
    forceWifiConnection(connectivityManager,wifiManager, ssid)
}

我也试图在ConnectivityManager中强制使用它:

private fun forceWifiConnection(connectivityManager: ConnectivityManager, wifiManager: WifiManager, currentSsid: String?) {
    val builder: NetworkRequest.Builder
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder = NetworkRequest.Builder()
        builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)

        connectivityManager.requestNetwork(builder.build(), object : ConnectivityManager.NetworkCallback() {
            override fun onAvailable(network: Network) {
                val ssid = wifiManager.connectionInfo.ssid
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    connectivityManager.bindProcessToNetwork(null)
                    if (ssid == "\"" + currentSsid + "\"") {
                        connectivityManager.bindProcessToNetwork(network)
                        connectivityManager.unregisterNetworkCallback(this)
                    }
                }
            }
        })
    }
}

但是,如果我通过系统设置(Wi-Fi设置)进行连接,则不会发生自动重新连接。通过编程连接后,我需要相同的行为。

0 个答案:

没有答案