连接到Wifi Android Q

时间:2019-09-25 05:59:46

标签: android android-wifi android-10.0

我正在尝试使用以下代码连接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$3.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.access$3200(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$3.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.access$3200(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()

根据文档说明:

  

此方法在API级别29中已弃用。   a)有关触发与Wi-Fi网络的连接的新机制,请参见WifiNetworkSpecifier.Builder#build()。 b)有关新的API,请参见addNetworkSuggestions(java.util.List),removeNetworkSuggestions(java.util.List),以添加Wi-Fi网络,以便在自动连接到wifi时考虑。兼容性说明:对于面向Build.VERSION_CODES.Q或更高版本的应用程序,此API始终返回false

我正在OS 9版本的真实设备中进行测试,但是代码在模拟器中运行良好。请告知可能的原因。谢谢您的帮助。

2 个答案:

答案 0 :(得分:2)

这是我的代码:

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"/>

答案 1 :(得分:0)

该类已在Api级别29中添加,因此如果您在android Pie上进行测试,它将无法正常工作。您需要包装检查构建版本的代码,并将其仅在android 10+上应用。