简体   繁体   English

连接WIFI时获取SSID

[英]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.当我的 android 设备连接到 WIFI 时,我试图获取 WIFI 网络的 SSID。

I've registered a BroadcastReceiver listening for android.net.wifi.supplicant.CONNECTION_CHANGE .我已经注册了一个 BroadcastReceiver 监听android.net.wifi.supplicant.CONNECTION_CHANGE I get the notification when WIFI is disconnected or reconnected.当 WIFI 断开或重新连接时,我会收到通知。 Unfortunately, I can't get the network's SSID.不幸的是,我无法获得网络的 SSID。

I'm using the following code to find the SSID:我正在使用以下代码来查找 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.我得到的不是 SSID,而是字符串<unknown ssid>

These are the permissions in the manifest (I've added ACCESS_NETWORK_STATE just to check, I don't actually need it)这些是清单中的权限(我添加了 ACCESS_NETWORK_STATE 只是为了检查,我实际上并不需要它)

<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?我怎样才能获得实际的 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.我只对 WIFI 连接感兴趣,对 3G 连接不感兴趣。

Update: I just checked, wifiInfo.getBSSID() returns null.更新:我刚刚检查过, wifiInfo.getBSSID()返回 null。

I listen for WifiManager.NETWORK_STATE_CHANGED_ACTION in a broadcast receiver我在广播接收器中监听 WifiManager.NETWORK_STATE_CHANGED_ACTION

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 ().我检查了 netInfo.isConnected()。 Then I am able to use然后我就可以使用

WifiManager wifiManager = (WifiManager) 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.从 android 8.0 开始,除非启用了位置服务并且您的应用程序有权访问它,否则我们将不会获得所连接网络的 SSID。

Starting with Android 8.1 (API 27), apps must be granted the ACCESS_COARSE_LOCATION (or ACCESS_FINE_LOCATION ) permission in order to obtain results from WifiInfo.getSSID() or WifiInfo.getBSSID() .从 Android 8.1 (API 27) 开始,应用程序必须被授予ACCESS_COARSE_LOCATION (或ACCESS_FINE_LOCATION )权限才能从WifiInfo.getSSID()WifiInfo.getBSSID()获取结果。 Apps that target API 29 or higher (Android 10) must be granted ACCESS_FINE_LOCATION .必须授予ACCESS_FINE_LOCATION API 29 或更高版本 (Android 10) 的应用程序ACCESS_FINE_LOCATION

This permission is also needed to obtain results from WifiManager.getConnectionInfo() and WifiManager.getScanResults() although it is not clear if this is new in 8.1 or was required previously.WifiManager.getConnectionInfo()WifiManager.getScanResults()获取结果也需要此权限,尽管尚不清楚这是 8.1 中的新功能还是以前需要。

Source : "BSSID/SSID can be used to deduce location, so require the same location permissions for access to these WifiInfo fields requested using WifiManager.getConnectionInfo() as for WifiManager.getScanResults()." 来源:“BSSID/SSID 可用于推断位置,因此使用 WifiManager.getConnectionInfo() 请求访问这些 WifiInfo 字段需要与 WifiManager.getScanResults() 相同的位置权限。”

If you don't want to make Broadcast Receiver then simple try如果你不想制作广播接收器,那么简单的尝试

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo;

wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo.getSupplicantState() == SupplicantState.COMPLETED) {
    ssid = wifiInfo.getSSID();
}

Remember every time user disconnect or connect to new SSID or any wifi state change then you need to initialize WifiInfo ie wifiInfo = wifiManager.getConnectionInfo();请记住,每次用户断开连接或连接到新的 SSID 或任何 wifi 状态更改时,您都需要初始化 WifiInfo,即wifiInfo = wifiManager.getConnectionInfo();

I found interesting solution to get SSID of currently connected Wifi AP.我找到了有趣的解决方案来获取当前连接的 Wifi AP 的 SSID。 You simply need to use iterate WifiManager.getConfiguredNetworks() and find configuration with specific WifiInfo.getNetworkId()您只需要使用迭代WifiManager.getConfiguredNetworks()并找到具有特定WifiInfo.getNetworkId()配置

My example我的例子

in Broadcast receiver with action WifiManager.NETWORK_STATE_CHANGED_ACTION I'm getting current connection state from intent在具有操作WifiManager.NETWORK_STATE_CHANGED_ACTION广播接收器中,我从意图中获取当前连接状态

NetworkInfo nwInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
nwInfo.getState()

If NetworkInfo.getState is equal to NetworkInfo.State.CONNECTED then i can get current WifiInfo object如果NetworkInfo.getState等于NetworkInfo.State.CONNECTED那么我可以获得当前的 WifiInfo 对象

WifiManager wifiManager = (WifiManager) getSystemService (Context.WIFI_SERVICE);
WifiInfo info = wifiManager.getConnectionInfo ();

And after that在那之后

public String findSSIDForWifiInfo(WifiManager manager, WifiInfo wifiInfo) {

    List<WifiConfiguration> listOfConfigurations = manager.getConfiguredNetworks();

    for (int index = 0; index < listOfConfigurations.size(); index++) {
        WifiConfiguration configuration = listOfConfigurations.get(index);
        if (configuration.networkId == wifiInfo.getNetworkId()) {
            return configuration.SSID;
        }
    }

    return null;
}

And very important thing this method doesn't require Location nor Location Permisions非常重要的是,此方法不需要位置或位置权限

In API29 Google redesigned Wifi API so this solution is outdated for Android 10.在 API29 中,Google 重新设计了 Wifi API,因此该解决方案对于 Android 10 已过时。

In Android 8.1 it is must to turned Location on to get SSID, if not you can get connection state but not SSID在 Android 8.1 中,必须打开 Location 才能获取 SSID,否则您可以获取连接状态但不能获取 SSID

WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = null;
if (wifiManager != null) 
wifiInfo = wifiManager.getConnectionInfo();
 String ssid = null;
if (wifiInfo != null) 
ssid = wifiInfo.getSSID(); /*you will get SSID <unknown ssid> if location turned off*/

This is a follow up to the answer given by @EricWoodruff.这是@EricWoodruff 给出的答案的后续。

You could use netInfo 's getExtraInfo() to get wifi SSID.您可以使用netInfogetExtraInfo()来获取 wifi SSID。

if (WifiManager.NETWORK_STATE_CHANGED_ACTION.equals (action)) {
    NetworkInfo netInfo = intent.getParcelableExtra (WifiManager.EXTRA_NETWORK_INFO);
    if (ConnectivityManager.TYPE_WIFI == netInfo.getType ()) {
        String ssid = info.getExtraInfo()
        Log.d(TAG, "WiFi SSID: " + ssid)
    }
}

If you are not using BroadcastReceiver check this answer to get SSID using Context如果您不使用 BroadcastReceiver,请检查答案以使用Context获取 SSID

This is tested on Android Oreo 8.1.0这是在 Android Oreo 8.1.0 上测试的

Answer In Kotlin Give Permissions在 Kotlin 中回答授予权限

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



 private fun getCurrentNetworkDetail() {
    val connManager =
        context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
    val networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
    if (networkInfo.isConnected) {
        val wifiManager =
            context.getApplicationContext().getSystemService(Context.WIFI_SERVICE) as WifiManager
        val connectionInfo = wifiManager.connectionInfo
        if (connectionInfo != null && !TextUtils.isEmpty(connectionInfo.ssid)) {
            Log.e("ssid", connectionInfo.ssid)
        }
    }
    else{
        Log.e("ssid", "No Connection")
    }

}

对我来说,它只有在我设置手机本身的权限时才有效(设置 -> 应用程序权限 -> 位置始终开启)。

According to the explanation of the official document, on Android 10+(API 29 and higher) , declaring ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permissions is not enough.根据官方文档的解释,在Android 10+(API 29及更高版本)上,声明ACCESS_COARSE_LOCATIONACCESS_FINE_LOCATION权限是不够的。

1. For foreground location: 1. 对于前景位置:

You also need to declare a foregroundServiceType of location in your Service to use foreground location.您还需要在您的服务中声明locationforegroundServiceType以使用前台位置。

<service
    android:name="MyNavigationService"
    android:foregroundServiceType="location" ... >
    <!-- Any inner elements would go here. -->
</service>

Or if your code running in the Activity, the activity should be visible to the user.或者,如果您的代码在 Activity 中运行,则该 Activity 应该对用户可见。

2. For background location: 2. 后台位置:

You should declare the ACCESS_BACKGROUND_LOCATION permission in your app's manifest in order to request background location access at runtime.您应该在应用的清单中声明ACCESS_BACKGROUND_LOCATION权限,以便在运行时请求后台位置访问。

Note: The Google Play Store has a location policy concerning device location, restricting background location access to apps that need it for their core functionality and meet related policy requirements.注意:Google Play 商店有一个关于设备位置的位置政策,限制了需要它来实现核心功能并满足相关政策要求的应用程序的后台位置访问。

Official document:官方文件:

https://developer.android.com/training/location/permissions https://developer.android.com/guide/topics/connectivity/wifi-scan#wifi-scan-permissions https://developer.android.com/training/location/permissions https://developer.android.com/guide/topics/connectivity/wifi-scan#wifi-scan-permissions

Check via NetworkInfo for wifi-type if it is connected. 如果已连接,请通过NetworkInfo检查wifi类型。 And then use wifiinfo getSSid(). 然后使用wifiinfo getSSid()。 You might want to remove double slashes from returnd SSID 您可能希望从returnnd SSID中删除双斜杠

https://play.google.com/store/apps/details?id=com.connect.freewifi https://play.google.com/store/apps/details?id=com.connect.freewifi

You should check out this application and developer api from http://developer.android.com/reference/android/net/wifi/WifiInfo.html 您应该从http://developer.android.com/reference/android/net/wifi/WifiInfo.html查看此应用程序和开发人员API。

It will help you with your task. 它将帮助您完成任务。

Android 9 SSID showing NULL values use this code..显示 NULL 值的 Android 9 SSID 使用此代码..

ConnectivityManager connManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (networkInfo.isConnected()) {
            WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            wifiInfo.getSSID();
            String name = networkInfo.getExtraInfo();
            String ssid = wifiInfo.getSSID();
            return ssid.replaceAll("^\"|\"$", "");
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM