Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

android - Get SSID when WIFI is connected

I'm trying to get the SSID of the WIFI network when my android device is connected to WIFI.

I've registered a BroadcastReceiver listening for android.net.wifi.supplicant.CONNECTION_CHANGE . I get the notification when WIFI is disconnected or reconnected. Unfortunately, I can't get the network's SSID.

I'm using the following code to find the SSID:

WifiManager wifiManager = (WifiManager) context.getSystemService(context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();

Instead of the SSID, I get the string <unknown ssid> back.

These are the permissions in the manifest (I've added ACCESS_NETWORK_STATE just to check, I don't actually need it)

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Why does this happen? How can I get the actual SSID? Is the broadcast fired to early, before the connection is established? Is there another broadcast I should listen to? I'm only interested in WIFI connections, not 3G connections.

Update: I just checked, wifiInfo.getBSSID() returns null.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I listen for WifiManager.NETWORK_STATE_CHANGED_ACTION in a broadcast receiver

if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action)) {
    NetworkInfo netInfo = intent.getParcelableExtra (WifiManager.EXTRA_NETWORK_INFO);
    if (ConnectivityManager.TYPE_WIFI == netInfo.getType ()) {
        ...
    }
}

I check for netInfo.isConnected(). Then I am able to use

WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo();
String ssid  = info.getSSID();

UPDATE

From android 8.0 onwards we wont be getting SSID of the connected network unless location services are enabled and your app has the permission to access it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...