How to get current wifi connection name in android

2019-07-13 05:40发布

问题:

I know it is very simple for you. Here I am just tried to get WiFi name in android pie devices. I am able to get WiFi name till Nogout devices with the help of below line of code.

 String ssid = wifiInfo.getSSID();

I have tried lots of answer and Android developer docs but unfortunately, I can not get a WiFi name on my mobile(Nokia 6.1 plus). I Know I am doing mistakes.

I just want a code there I can get a wifi name from my mobile to my android studio logcat.

回答1:

This is related to permissions....since API level 27 you need either ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permission. You may also need CHANGE_WIFI_STATE for Android 9 (that's the case for wifi scan anyway as per google permisson model

then try this code

   ConnectivityManager connManager = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (networkInfo.isConnected()) {
            WifiManager wifiManager = (WifiManager) activity.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            wifiInfo.getSSID();
            String name = networkInfo.getExtraInfo();
            String ssid = "\"" + wifiInfo.getSSID() + "\"";
}


回答2:

Try to get SSID value using

 WifiManager wifiManager = (WifiManager) 
 context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
 wifiInfo = wifiManager.getConnectionInfo();

if it returns SSID as null, then turn on the location and try the same. Oreo 8.1+ devices require the coarse location runtime permission as well as location services to be turned on before retrieving the connected SSID.

Check this link