Android WIFI网络连接

1.权限

    
    

2.获取WifiManager

val wifiManager = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            application.getSystemService(WifiManager::class.java)
        } else {
            application.applicationContext.getSystemService(Context.WIFI_SERVICE)?.let {
                it as WifiManager
            }
        }

3.注册扫描结果广播接收器

 val intentFilter = IntentFilter(SCAN_RESULTS_AVAILABLE_ACTION)
 AppUtilsHelper.mContext.registerReceiver(WifiScanReceiver(),intentFilter)
  • 广播接收器
   private inner class WifiScanReceiver: BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            context?.let {
                val wifiManager =  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    it.getSystemService(WifiManager::class.java)
                } else {
                    it.applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
                }
                 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//大于6.0的版本
                     val success = intent?.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false)
                     if (success == null || !success){//失败
                         //此时获取的scanResults可能为空或者是之前老的扫描结果
                         mResult(false,wifiManager.scanResults)
                     }else{//成功
                         //此时获取的是最新的扫描结果
                         mResult(true,wifiManager.scanResults)
                     }
                } else {//小于6.0的版本
                    mResult(true,wifiManager.scanResults)
                }

            }
        }

    }

4.扫描

val wifiManager = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            AppUtilsHelper.mContext.getSystemService(WifiManager::class.java)
        } else {
            AppUtilsHelper.mContext.applicationContext.getSystemService(Context.WIFI_SERVICE)?.let {
                it as WifiManager
            }
        }
        val success = wifiManager?.startScan()
        if (success ==  null || !success){
            //失败则直接返回空或老的扫描结果,成功则去广播接收器中获取结果
            mResult(false,wifiManager?.scanResults)
        }

5.限制概述(权限与节流)

  • Android 8.0、8.1

WifiManager.getScanResults()成功获取扫描结果的必要条件,获取以下任意一项权限:

  • ACCESS_FINE_LOCATION
  • ACCESS_COARSE_LOCATION
  • CHANGE_WIFI_STATE

注意:后台应用可以30分钟扫描一次

  • Android 9

WifiManager.startScan()成功调用扫描必须满足以下所有条件:

  • ACCESS_FINE_LOCATION 或 ACCESS_COARSE_LOCATION(开启)
  • CHANGE_WIFI_STATE(开启)
  • 设备已启用位置服务

注意: 前台应用每2分钟可以扫描四次,后台应用可以30分钟扫描一次

  • Android 10

WifiManager.startScan()需满足以下所有条件:

  • ACCESS_FINE_LOCATION(开启)
  • ACCESS_WIFI_STATE(开启)
  • 设备已启用位置服务

WifiManager.getScanResults()需满足以下所有条件:

  • ACCESS_FINE_LOCATION ACCESS_COARSE_LOCATION(开启)
  • ACCESS_WIFI_STATE(开启)
  • 设备已启用位置服务

6.WIFI连接

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {//Android Q及其以上版本
            val wifiNetworkSpecifier = WifiNetworkSpecifier.Builder()
                .setSsid(ssid)
                .setWpa2Passphrase(psd)
                .build()
            val networkRequest = NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .setNetworkSpecifier(wifiNetworkSpecifier)
                .build()
            application.getSystemService(ConnectivityManager::class.java)?.requestNetwork(networkRequest,
                object : ConnectivityManager.NetworkCallback() {
                    override fun onAvailable(network: Network) {
                        super.onAvailable(network)
                        Log.e("===", "==onAvailable===")

                    }

                    override fun onLost(network: Network) {
                        super.onLost(network)
                        Log.e("===", "==onLost===")

                    }

                    override fun onUnavailable() {
                        super.onUnavailable()
                        Log.e("===", "==onUnavailable===")

                    }
                })
        } else {小于Android Q的版本
            val wifiSSID = "\"" + ssid + "\""
            val wifiConfiguration = WifiConfiguration().apply {
                SSID = wifiSSID
                preSharedKey = "\"" + psd + "\""
                hiddenSSID = true
                allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
                allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
                allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
                allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
                allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
                allowedProtocols.set(WifiConfiguration.Protocol.RSN)
                status = WifiConfiguration.Status.ENABLED
//                wepKeys[0] = "\"" +psd+ "\""
//                wepTxKeyIndex = 0
//                allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
//                allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40)
            }
            val wifiManager = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                application.getSystemService(WifiManager::class.java)
            } else {
                application.applicationContext.getSystemService(Context.WIFI_SERVICE)
                    ?.let {
                        it as WifiManager
                    }

            }
            wifiManager?.run {
                 addNetwork(wifiConfiguration)
                val config=  configuredNetworks.first {
                    it.SSID != null && it.SSID == wifiSSID
                }
                disconnect()
                Log.e("===","==networkId==${config.networkId}")
                val enableNetwork = enableNetwork(config.networkId, true)
                Log.e("===","==enableNetwork==$enableNetwork")
                val b = reconnect()
                Log.e("==","==reconnect=====$b")
            }

        }

NOTE:不要使用addNetwork(wifiConfiguration)返回的networkId,在部分机型中永远都是-1。

你可能感兴趣的:(Android WIFI网络连接)