【 Android11 WiFi开发 三 】WiFi信息获取与静态IP设置

前言

继续记录Android11上WiFi功能的开发,前面文章介绍了WiFi列表的获取展示,WiFi的连接与断开,那么本篇将介绍WiFi信息获取、静态IP设置。


相关文章

1、【 Android11 WiFi开发 一 】WiFi列表获取与展示

2、【 Android11 WiFi开发 二 】WiFi连接、断开


说明

WiFi信息获取针对的是已连接的WiFi,显示其ip地址、默认网关gateway、子网掩码subnetmaskdns服务器地址。需求相对较为简单,这里就不画流程图,直接看实现。


实现


1、获取连接对象

获取ConnectivityManager对象,这个是网络连接管理类,可获取网络是否连接,连接的网络类型、连接的网络的信息。

 	private val wifiManager:WifiManager = App.context.getSystemService(Context.WIFI_SERVICE) as WifiManager

    private val connectivityManager = App.context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    

声明无线网络数据类

	/**
 	* 无线网络信息model
 	*/
	data class Wireless(

	    //wifi名称
	    var SSID: String?,
	
	    //高级选项开关
	    var isDhcp: Boolean,
	
	    //IPv4
	    var ipv4: String?,
	
	    //子网掩码
	    var subnetMask: String?,
	
	    //默认网关
	    var gateway: String?,
	
	    //dns服务器
	    var dns :String?
	)	

2、获取WiFi信息

   	/**
     * 获取已连接的WiFi信息
     */
    fun getWiFiInfo(): Wireless {

        var ip = "0.0.0.0"
        var subnet = "0.0.0.0"
        var gateway = "0.0.0.0"
        var dns = "0.0.0.0"

        val info = wifiManager.connectionInfo
        val network = wifiManager.getCurrentNetwork()
        val lp = connectivityManager.getLinkProperties(network)
        if (lp != null) {
            lp.linkAddresses.forEach {
                if (it.address is Inet4Address) {
                    ip = it.address.hostAddress as String
                    subnet = ipv4PrefixLengthToSubnetMask(it.prefixLength).toString()
                }
            }

            lp.routes.forEach {
                if (it.isDefaultRoute && it.hasGateway()) {
                    gateway = it.gateway?.hostAddress.toString()
                }
            }

            if(gateway.isEmpty()){ gateway = "0.0.0.0" }

            dns = if(lp.dnsServers.size > 0){
                lp.dnsServers[0].hostAddress as String
            }else{
                "0.0.0.0"
            }
        }
        return Wireless(info?.ssid, isWiFiDHCP(), ip, subnet, gateway,dns)
    }

	/**
	 * 转为子网掩码
	 */
	private fun ipv4PrefixLengthToSubnetMask(prefixLength: Int): String? {
       return try {
            val all = InetAddress.getByAddress(byteArrayOf(255.toByte(), 255.toByte(), 255.toByte(), 255.toByte()))
            NetworkUtils.getNetworkPart(all, prefixLength).hostAddress
        } catch (e: UnknownHostException) {
            null
        }
    }



    /**
     * WiFi ip是否是自动获取
     */
    private fun isWiFiDHCP(): Boolean {
        val dhcpInfo: DhcpInfo = wifiManager.dhcpInfo
        return dhcpInfo.leaseDuration != 0
    }


3、设置WiFi有静态ip地址

    /**
     * 设置WiFi为静态ip地址
     */
    fun setWiFiWithStaticIP(w:Wireless,proxy:Boolean):Boolean{
        var success = false
        val ipConfig:IpConfiguration
        if(!isWiFiEnabled()){ return false }
        val wifiConfig = getWiFiConfig(w.SSID)
        if(wifiConfig != null){
            ipConfig = wifiConfig.getIpConfiguration()
        }else{
            ipConfig = IpConfiguration()
        }
        try {
            var staticConfig = wifiConfig?.getStaticIpConfiguration()
            if(w.isDhcp){
                wifiConfig?.setIpAssignment(IpConfiguration.IpAssignment.DHCP)
                staticConfig?.clear()
            }else{
                if("0.0.0.0" == w.ipv4 || "0.0.0.0" == w.subnetMask || "0.0.0.0" == w.gateway || "0.0.0.0" == w.dns){
                    return false
                }
                wifiConfig?.setIpAssignment(IpConfiguration.IpAssignment.STATIC)
                if(staticConfig == null){
                    staticConfig = StaticIpConfiguration()
                }else{
                    staticConfig.clear()
                }
                if(TextUtils.isEmpty(w.ipv4)){
                    App.context.toast(R.string.wifi_invalid_ip_address)
                    return false
                }
                val inetAddress: InetAddress
                try {
                    inetAddress = NetworkUtils.numericToInetAddress(w.ipv4)
                }catch (e:Exception){
                    App.context.toast(R.string.wifi_invalid_ip_address)
                    return false
                }
                val netmaskPrefixLength = TestUtils.parsePrefixLength(w.subnetMask!!)
                try {
                    staticConfig!!.ipAddress = LinkAddress(inetAddress,netmaskPrefixLength)
                }catch (e:Exception){
                    App.context.toast(R.string.wifi_invalid_ip_address)
                    return false
                }
                if(!TextUtils.isEmpty(w.gateway)){
                    try {
                        staticConfig!!.gateway = NetworkUtils.numericToInetAddress(w.gateway) as Inet4Address
                    } catch (e: Exception) {
                        App.context.toast(R.string.wifi_invalid_gateway)
                        return false
                    }
                }
                if(!TextUtils.isEmpty(w.dns)){
                    try {
                        staticConfig!!.dnsServers.add(NetworkUtils.numericToInetAddress(w.dns))
                    }catch (e:Exception){
                        App.context.toast(R.string.wifi_invalid_dns)
                        return false
                    }
                }

                if(!TextUtils.isEmpty(w.dns)){
                    try {
                        staticConfig!!.dnsServers.add(NetworkUtils.numericToInetAddress(w.dns))
                    }catch (e:Exception){
                        App.context.toast(R.string.wifi_invalid_dns)
                        return false
                    }
                }
                ipConfig.setStaticIpConfiguration(staticConfig)
            }

            if(!proxy){
                wifiConfig?.setIpConfiguration(IpConfiguration(wifiConfig.getIpAssignment(), IpConfiguration.ProxySettings.NONE, staticConfig, null))
                saveConfiguration(wifiConfig!!)
                updateConfiguration(wifiConfig)
                disconnectWiFi()
                reconnectWiFi()
            }
            success = true
        }catch (e:Exception){
            e.printStackTrace()
        }
        return success
    }

设置静态ip地址需要的类有WifiConfiguration 用于保存WiFi配置。 IpConfiguration 用于IP状态配置,动态或者是静态。StaticIpConfiguration主要用于配置静态IP地址等。

   
    /**
     * 保存WiFi配置
     */
    private fun saveConfiguration(config:WifiConfiguration){
        wifiManager.save(config,null)
    }
    

 	/**
     * 更新WiFi配置
     */
    private fun updateConfiguration(config:WifiConfiguration){
        wifiManager.updateNetwork(config)
    }

	/**
     * WiFi断开连接
     */
    private fun disconnectWiFi():Boolean{
        return wifiManager.disconnect()
    }

    /**
     * 重新连接
     */
    private fun reconnectWiFi():Boolean{
        return wifiManager.reconnect()
    }

设置WiFi自动获取ip和静态ip设置流程是一致的,只是不需要用到StaticIpConfiguration去设置静态ip,将IpConfiguration配置设为动态即可。


    /**
     * 设置WiFi自动获取ip
     */
    fun setWiFiWithDHCP(proxy:Boolean,w:Wireless?):Boolean{
        if(!isWiFiEnabled()){ return false }
        val wifiConfig = getWiFiConfig(w?.SSID)
        val staticConfig = wifiConfig?.getStaticIpConfiguration()
        staticConfig?.clear()

        wifiConfig?.setIpAssignment(IpConfiguration.IpAssignment.DHCP)
        val ipConfig:IpConfiguration
        if(wifiConfig != null){
            ipConfig = wifiConfig.getIpConfiguration()
        }else{
            ipConfig = IpConfiguration()
        }
        ipConfig.setStaticIpConfiguration(staticConfig)
        wifiConfig?.setIpConfiguration(ipConfig)
        if(!proxy){
            wifiConfig?.setIpConfiguration(IpConfiguration(wifiConfig.getIpAssignment(), IpConfiguration.ProxySettings.NONE, wifiConfig.getStaticIpConfiguration(), null))
            saveConfiguration(wifiConfig!!)
            updateConfiguration(wifiConfig)
            disconnectWiFi()
            reconnectWiFi()
        }
        return true
    }
    
    /**
     * 获取当前SSID的WiFi配置
     * @param[ssid] 字符串或一串16进制的数字
     */
    fun getWiFiConfig(ssid: String?): WifiConfiguration? {
        val configs = wifiManager.configuredNetworks
        if(App.DEBUG) Log.i(TAG,"configs size = ${configs.size}")
        if (configs != null && configs.size > 0 ) {
            for( config in configs){
                if(App.DEBUG) Log.i(TAG,"config = $config")
                val configSSID = config.SSID.replace("\"", "")
                if (ssid == configSSID) return config
            }
        }
        return null
    }
    

结尾

以上介绍了WiFi信息的获取,可获取到ip地址、默认网关gateway、子网掩码subnetmaskdns服务器地址等。通过IpConfigurationStaticIpConfiguration设置动态和静态ip地址。

你可能感兴趣的:(Android网络,Android网络,Android,WiFi,安卓WiFi静态IP,安卓WiFi动态IP)