如何查看Android上是否已连接Wi-Fi? [英] How do I see if Wi-Fi is connected on Android?
问题描述
除非用户已连接Wi-Fi,否则我甚至不希望我的用户尝试下载某些内容.但是,我似乎只能说出是否启用了Wi-Fi,但他们仍然可以进行3G连接.
I don't want my user to even try downloading something unless they have Wi-Fi connected. However, I can only seem to be able to tell if Wi-Fi is enabled, but they could still have a 3G connection.
android.net.wifi.WifiManager m = (WifiManager) getSystemService(WIFI_SERVICE);
android.net.wifi.SupplicantState s = m.getConnectionInfo().getSupplicantState();
NetworkInfo.DetailedState state = WifiInfo.getDetailedStateOf(s);
if (state != NetworkInfo.DetailedState.CONNECTED) {
return false;
}
但是,状态不是我所期望的.即使已连接Wi-Fi,我仍会以OBTAINING_IPADDR
作为状态.
However, the state is not what I would expect. Even though Wi-Fi is connected, I am getting OBTAINING_IPADDR
as the state.
推荐答案
您应该能够使用ConnectivityManager来获取Wi-Fi适配器的状态.从那里您可以检查它是否已连接或什至可用. >
You should be able to use the ConnectivityManager to get the state of the Wi-Fi adapter. From there you can check if it is connected or even available.
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWifi.isConnected()) {
// Do whatever
}
注意:(请注意,对于我们这里的n00bies),您需要添加
NOTE: It should be noted (for us n00bies here) that you need to add
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
到您的
AndroidManifest.xml 才能正常工作.
此方法已在API级别23中弃用. 支持多个相同类型的连接网络.使用 而是使用getAllNetworks()和getNetworkInfo(android.net.Network).
This method was deprecated in API level 23. This method does not support multiple connected networks of the same type. Use getAllNetworks() and getNetworkInfo(android.net.Network) instead.
NOTE3 : public static final int TYPE_WIFI
现在已弃用:
NOTE3: public static final int TYPE_WIFI
is now deprecated:
此常数在API级别28中已弃用. 应用程序应该改用NetworkCapabilities.hasTransport(int)或requestNetwork(NetworkRequest,NetworkCallback)来请求适当的网络.用于支持的运输.
This constant was deprecated in API level 28. Applications should instead use NetworkCapabilities.hasTransport(int) or requestNetwork(NetworkRequest, NetworkCallback) to request an appropriate network. for supported transports.
这篇关于如何查看Android上是否已连接Wi-Fi?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!