欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android开发,如何知道Wi-Fi已连接了一个热点

程序员文章站 2022-03-11 23:17:13
如题,在Android Q(Android 10)以前,通过传统手段是能够轻松知道的。但是Android Q(Android 10)对设备的系统标识(MAC、IMEI、序列号)增加了更多的限制和修改,当我们用传统手段去获取时就行不通了。如果用户不授予相关权限,得到wifi信息中很多字段(如bssid、ssid将是默认值),那如何判断呢?1:获取WifiManager// Kotlin扩展函数val Context.wifi: Wi...

      如题,在Android Q(Android 10)以前,通过传统手段是能够轻松知道的。但是Android Q(Android 10)对设备的系统标识(MAC、IMEI、序列号)增加了更多的限制和修改,当我们用传统手段去获取时就行不通了。如果用户不授予相关权限,得到wifi信息中很多字段(如bssid、ssid将是默认值),那如何判断呢?
1:获取WifiManager

// Kotlin扩展函数
val Context.wifi: WifiManager
    get() = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager

2:获取当前连接信息WifiInfo

if (wifi.isWifiEnabled) {
	// Wi-Fi模块开启,获取连接信息
	val info = wifi.connectionInfo
	// 
	if(SupplicantState.DISCONNECTED == wifi.connectionInfo.supplicantState) {
		// 可以判定未连接到热点,不授予位置权限也能成功判断
	}
}

备注:
在Android 10中,bssid,ssid将不可靠,具体可看WifiInfo源码介绍的注释,在没有权限的时候不管是否连接wifi,获取到的bssid是"02:00:00:00:00:00",获取到的ssid是"< unknown ssid >"

    /**
     * Return the basic service set identifier (BSSID) of the current access point.
     * <p>
     * The BSSID may be
     * <lt>{@code null}, if there is no network currently connected.</lt>
     * <lt>{@code "02:00:00:00:00:00"}, if the caller has insufficient permissions to access the
     * BSSID.<lt>
     * </p>
     *
     * @return the BSSID, in the form of a six-byte MAC address: {@code XX:XX:XX:XX:XX:XX}
     */
    public String getBSSID() {
        return mBSSID;
    }
/**
     * Returns the service set identifier (SSID) of the current 802.11 network.
     * <p>
     * If the SSID can be decoded as UTF-8, it will be returned surrounded by double
     * quotation marks. Otherwise, it is returned as a string of hex digits.
     * The SSID may be
     * <lt>&lt;unknown ssid&gt;, if there is no network currently connected or if the caller has
     * insufficient permissions to access the SSID.<lt>
     * </p>
     * <p>
     * Prior to {@link android.os.Build.VERSION_CODES#JELLY_BEAN_MR1}, this method
     * always returned the SSID with no quotes around it.
     * </p>
     *
     * @return the SSID.
     */
    public String getSSID() {
        if (mWifiSsid != null) {
            String unicode = mWifiSsid.toString();
            if (!TextUtils.isEmpty(unicode)) {
                return "\"" + unicode + "\"";
            } else {
                String hex = mWifiSsid.getHexString();
                return (hex != null) ? hex : WifiSsid.NONE;
            }
        }
        return WifiSsid.NONE;
    }

本文地址:https://blog.csdn.net/xiaocheng0404/article/details/107375780

相关标签: 适配 android