如何在 android Q 及更高版本中获取已连接 wifi 的 SSID?

问题描述

我之前的 android Q 代码在这里 但是对于 android Q 这个函数返回“unkNown ssid”。 我知道对于 android Q 必须使用这个 ConnectivityManager.NetworkCallback 和 ConnectivityManager#getNetworkCapabilities 和 ConnectivityManager#getLinkProperties。但我找不到示例代码或 guid。

private String get_connected_ssid() {

    String s1 = null,s2 = null;
    try {
        WifiManager wifi = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        assert wifi != null;
        WifiInfo wifiinfo = wifi.getConnectionInfo();

        List<WifiConfiguration> listofConfigurations = wifi.getConfigurednetworks();

        for (int index = 0; index < listofConfigurations.size(); index++) {

            WifiConfiguration configuration = listofConfigurations.get(index);

            if (configuration.networkId == wifiinfo.getNetworkId()) {
                s1 = configuration.SSID;
            }
        }
    }catch (Exception e){
        e.printstacktrace();
    }
      /*     NetworkInfo Deprecated in API level 29
             Callers should instead use the ConnectivityManager.NetworkCallback API to learn about connectivity changes,or switch to use ConnectivityManager#getNetworkCapabilities or ConnectivityManager#getLinkProperties to
             get information synchronously. Keep in mind that while callbacks are guaranteed to be called for every
             event in order,synchronous calls have no such constraints,and as such it is unadvisable to use the
             synchronous methods inside the callbacks as they will often not offer a view of networking that is
             consistent (that is: they may return a past or a future state with respect to the event being processed
             by the callback). Instead,callers are advised to only use the arguments of the callbacks,possibly
             memorizing the specific bits of information they need to keep from one callback to another.
             */
    //getActiveNetworkInfo Deprecated in API level 29 -->useUse NetworkCallbacks instead for apps that target Android 10 (API level 29) and higher-->refrence : developer.android
    //getExtraInfo() Deprecated in API level 29
    try {
        ConnectivityManager cm = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        assert cm != null;
        NetworkInfo info = cm.getActiveNetworkInfo();
        if (info != null && info.isConnected()) {
        }
    }catch (Exception e){
        e.printstacktrace();
    }
    return s1 + s2;
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)