连接到 Wifi Android 问

Connect To Wifi Android Q

我正在尝试使用以下代码连接到 wifi

 val specifier = WifiNetworkSpecifier.Builder()
        .setSsid(machineID).build()

    val networkRequest = NetworkRequest.Builder()
        .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
        .setNetworkSpecifier(specifier)
        .build()

    val connectivityManager = context.applicationContext
        .getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?

    connectivityManager?.requestNetwork(networkRequest,object:ConnectivityManager.NetworkCallback(){
        override fun onUnavailable() {
            callback.onWifiConnected(WifiConstant.WIFI_IP_ADDRESS_INVALID)
        }

        override fun onAvailable(network: Network) {
            val wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)

            if (wifiInfo.isConnected)
                callback.onWifiConnected("${getWifiManager()?.connectionInfo?.ipAddress!!}")
            else
                callback.onWifiConnected(WifiConstant.WIFI_IP_ADDRESS_INVALID)
        }
    })

但我总是在这一行遇到运行时错误

val specifier = WifiNetworkSpecifier.Builder()

错误如下:

2019-09-25 13:49:00.718 28556-28556/com.aloha.asiaiot E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.aloha.asiaiot, PID: 28556
java.lang.NoClassDefFoundError: Failed resolution of: Landroid/net/wifi/WifiNetworkSpecifier$Builder;
    at com.aloha.asiaiot.common.util.wifi.WifiConnectionManager.connectToWifi(WifiConnectionManager.kt:77)
    at com.aloha.asiaiot.connectivity.devicescan.data.DeviceScanNetworkRepository.connectToWifi(DeviceScanNetworkRepository.kt:48)
    at com.aloha.asiaiot.connectivity.devicescan.domain.DeviceScanRepository.connectToWifi(DeviceScanRepository.kt:18)
    at com.aloha.asiaiot.connectivity.devicescan.domain.DeviceScanUseCase.connectToWifi(DeviceScanUseCase.kt:18)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.viewmodel.DeviceScanViewModel.connectToWifi(DeviceScanViewModel.kt:41)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment.connectToGateway(DeviceScanFragment.kt:139)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment.access$connectToGateway(DeviceScanFragment.kt:29)
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment$onActivityCreated.onClick(DeviceScanFragment.kt:72)
    at android.view.View.performClick(View.java:7339)
    at android.widget.TextView.performClick(TextView.java:14221)
    at android.view.View.performClickInternal(View.java:7305)
    at android.view.View.access00(View.java:846)
    at android.view.View$PerformClick.run(View.java:27787)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7058)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
 Caused by: java.lang.ClassNotFoundException: Didn't find class "android.net.wifi.WifiNetworkSpecifier$Builder" on path: DexPathList[[zip file "/data/app/com.aloha.asiaiot-k57tcS1ybEKsaCIu13TJnw==/base.apk"],nativeLibraryDirectories=[/data/app/com.aloha.asiaiot-k57tcS1ybEKsaCIu13TJnw==/lib/arm64, /system/lib64]]
    at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
    at com.aloha.asiaiot.common.util.wifi.WifiConnectionManager.connectToWifi(WifiConnectionManager.kt:77) 
    at com.aloha.asiaiot.connectivity.devicescan.data.DeviceScanNetworkRepository.connectToWifi(DeviceScanNetworkRepository.kt:48) 
    at com.aloha.asiaiot.connectivity.devicescan.domain.DeviceScanRepository.connectToWifi(DeviceScanRepository.kt:18) 
    at com.aloha.asiaiot.connectivity.devicescan.domain.DeviceScanUseCase.connectToWifi(DeviceScanUseCase.kt:18) 
    at com.aloha.asiaiot.connectivity.devicescan.presentation.viewmodel.DeviceScanViewModel.connectToWifi(DeviceScanViewModel.kt:41) 
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment.connectToGateway(DeviceScanFragment.kt:139) 
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment.access$connectToGateway(DeviceScanFragment.kt:29) 
    at com.aloha.asiaiot.connectivity.devicescan.presentation.DeviceScanFragment$onActivityCreated.onClick(DeviceScanFragment.kt:72) 
    at android.view.View.performClick(View.java:7339) 
    at android.widget.TextView.performClick(TextView.java:14221) 
    at android.view.View.performClickInternal(View.java:7305) 
    at android.view.View.access00(View.java:846) 
    at android.view.View$PerformClick.run(View.java:27787) 
    at android.os.Handler.handleCallback(Handler.java:873) 
    at android.os.Handler.dispatchMessage(Handler.java:99) 
    at android.os.Looper.loop(Looper.java:214) 
    at android.app.ActivityThread.main(ActivityThread.java:7058) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965) 

2019-09-25 13:49:00.747 28556-28556/com.aloha.asiaiot

我也尝试使用以下代码来解决较低的 SDK 问题:

 if (Build.VERSION.SDK_INT< Build.VERSION_CODES.Q) {
        val wifiConfiguration = WifiConfiguration()
    wifiConfiguration.SSID = String.format("\"%s\"", machineID)
    wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
    wifiConfiguration.status = WifiConfiguration.Status.ENABLED
    wifiConfiguration.priority = 40

    val wifiManager = getWifiManager()
    val netID = wifiManager?.addNetwork(wifiConfiguration)!!

    wifiManager.disconnect()
    wifiManager.enableNetwork(netID,true)
    wifiManager.reconnect()


    if (isWifiConnected(machineID))
        callback.onWifiConnected("${wifiManager.dhcpInfo.ipAddress}")
    else
        callback.onWifiConnected(WifiConstant.WIFI_IP_ADDRESS_INVALID)
    }

在我的 isWifiConnected 下面:

private fun isWifiConnected (machineID: String) : Boolean{
    if (getWifiManager()?.isWifiEnabled!!) {
        val wifiInfo = getWifiManager()?.connectionInfo
        if (wifiInfo?.ssid==machineID)
            return true
    }

    return false
}

但是在这部分我总是报错:

    wifiManager.disconnect()
    wifiManager.enableNetwork(netID,true)
    wifiManager.reconnect()

根据文档,它说:

This method was deprecated in API level 29. a) See WifiNetworkSpecifier.Builder#build() for new mechanism to trigger connection to a Wi-Fi network. b) See addNetworkSuggestions(java.util.List), removeNetworkSuggestions(java.util.List) for new API to add Wi-Fi networks for consideration when auto-connecting to wifi. Compatibility Note: For applications targeting Build.VERSION_CODES.Q or above, this API will always return false.

我正在使用 OS 版本 9 在真实设备中进行测试。但是代码 运行 在模拟器中没问题。请告知可能的原因是什么。感谢您的帮助。

class 已添加到 Api 级别 29,因此如果您在 android Pie 上进行测试,它将无法运行。您需要包装您的代码以检查构建版本并将其仅应用于 android 10+.

这是我的代码:

val wifiManager = applicationContext.getSystemService(WIFI_SERVICE) as WifiManager?
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
        try {
            val wifiConfig = WifiConfiguration()
            wifiConfig.SSID = "\"" + yourSsid + "\""
            wifiConfig.preSharedKey = "\"" + password + "\""
            val netId = wifiManager!!.addNetwork(wifiConfig)
            wifiManager.disconnect()
            wifiManager.enableNetwork(netId, true)
            wifiManager.reconnect()
            if (isWifiConnected("\"" + deviceId + "\"")) {
                doSomethingHere()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    } else {
        val wifiNetworkSpecifier = WifiNetworkSpecifier.Builder()
                .setSsid( yourSsid!! )
                .setWpa2Passphrase(password)
                .build()

        val networkRequest = NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .setNetworkSpecifier(wifiNetworkSpecifier)
                .build()

        connectivityManager = Boron.instance.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager?

        networkCallback = object : ConnectivityManager.NetworkCallback() {
            override fun onUnavailable() {
                super.onUnavailable()
            }

            override fun onLosing(network: Network, maxMsToLive: Int) {
                super.onLosing(network, maxMsToLive)

            }

            override fun onAvailable(network: Network) {
                super.onAvailable(network)
                connectivityManager?.bindProcessToNetwork(network)
            }

            override fun onLost(network: Network) {
                super.onLost(network)

            }
        }
        connectivityManager?.requestNetwork(networkRequest,networkCallback)
    }

然后在onDestroy connectivityManager?.unregisterNetworkCallback(networkCallback)

需要权限:

 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-feature android:name="android.permission.WRITE_SETTINGS"
    android:required="false"/>