android10获取WiFi名称 已经连接的WiFi名称 SSID

WifiManager.NETWORK_STATE_CHANGED_ACTION 广播在Android9.0还有效,Android10.0已经无效了。

WifiInfo wifiInfo = intent.getParcelableExtra(WifiManager.EXTRA_WIFI_INFO);
String bssid = intent.getStringExtra(WifiManager.EXTRA_BSSID);

解决办法:
android10如果要用到wifi相关的api时要引用ACCESS_FINE_LOCATION 或 ACCESS_COARSE_LOCATION权限。
添加权限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

使用方法:


public static String getWIFISSID(Activity activity) {
    String ssid = "unknown id";
 
    if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O || Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
 
        WifiManager mWifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
 
        assert mWifiManager != null;
        WifiInfo info = mWifiManager.getConnectionInfo();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            return info.getSSID();
        } else {
            return info.getSSID().replace("\"", "");
        }
    } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1) {
 
        ConnectivityManager connManager = (ConnectivityManager) activity.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        assert connManager != null;
        NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
        if (networkInfo.isConnected()) {
            if (networkInfo.getExtraInfo() != null) {
                return networkInfo.getExtraInfo().replace("\"", "");
            }
        }
    }
    return ssid;

原文链接:
Android10的WIFI 名称读取为空解决

posted @ 2022-03-12 22:04  xiaomodecnblogs  阅读(1205)  评论(0编辑  收藏  举报