如何在 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 使其正常工作.
注意2:public NetworkInfo getNetworkInfo (int networkType)
现已弃用:
NOTE2: public NetworkInfo getNetworkInfo (int networkType)
is now deprecated:
此方法已在 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 intTYPE_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屋!