Wifi getSSID() 返回 null [英] Wifi getSSID() returns null
问题描述
我使用 getSSID() 在建立新连接后立即获取 wifi 网络的名称.但有时我会为该值获取空值.这是我的代码:
I use getSSID() to get the name of the wifi network as soon as a new connection is made. But sometimes I get null for that value. This is my code:
清单中的权限是正确的,因为正如我所说,它在大多数情况下都有效.
Permissions in manifest are correct, because, as I said, most of the times it works.
我将此过滤器用于广播接收器:
I use this filter for the broadcast receiver:
<action android:name="android.net.wifi.supplicant.CONNECTION_CHANGE" />
在广播中我这样做:
if("android.net.wifi.supplicant.CONNECTION_CHANGE".equals(intent.getAction()))
{ boolean bConected = intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false);
if(bConnected == true)
{ WifiManager wifi = (WifiManager) Contexto.getSystemService(Context.WIFI_SERVICE);
String MyName = wifi.getConnectionInfo().getSSID();
Sometimes MyName is null here even if Wifi is connected correctly
}
}
有什么想法吗?
推荐答案
我经常使用类似的代码,但我从来没有在连接时收到null
.
I use similar code regularly and I have never received null
when connected.
这是我的代码:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String myName = info.getSSID();
因此,我建议您在收到CONNECTION_CHANGE
广播后等待400到1000ms左右,然后再请求信息.
Therefore, I propose that you should wait 400 to 1000ms or so after receipt of the CONNECTION_CHANGE
broadcast before requesting the information.
这是一个实现延迟的示例:
Here is one example that will implement the delay:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String myName = info.getSSID();
}
}, 1000);
这篇关于Wifi getSSID() 返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!