如何确定Android互联网连接? [英] How to determine Android internet connection?
问题描述
如何确定 Android 设备当前可用的互联网连接类型?例如让它返回 WiFi,3G,无.
How can I determine the current internet connection type available to an Android device? e.g. have it return WiFi, 3G, none.
推荐答案
你可以用这个来判断你是否已连接:
You can use this to determine whether you are connected:
final ConnectivityManager connectManager = (ConnectivityManager)ctx.getSystemService(Context.CONNECTIVITY_SERVICE); // ctx stands for the Context
final NetworkInfo mobile = connectManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
final NetworkInfo wifi = connectManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI );
// Return true if connected, either in 3G or wi-fi
return ((mobile != null && mobile.getState() == NetworkInfo.State.CONNECTED) ||
(wifi != null && wifi.getState() == NetworkInfo.State.CONNECTED) );
}
此代码需要权限ACCESS_NETWORK_STATE
和ACCESS_WIFI_STATE
.
编辑:public NetworkInfo getNetworkInfo (int networkType)
已在 API 21 中弃用.对于高于 20 的 API 级别,您可以执行以下操作:
EDIT: public NetworkInfo getNetworkInfo (int networkType)
has been deprecated in API 21. For API levels higher than 20 you can do as follows:
final Network[] networks = connectManager.getAllNetworks();
boolean connected = false;
for (int ctr = 0; !connected && ctr < networks.length; ++ctr) {
final NetworkInfo network = connectManager.getNetworkInfo(networks[ctr]);
final int netType = network.getType();
connected = (network.getState() == NetworkInfo.State.CONNECTED) &&
(
netType == ConnectivityManager.TYPE_MOBILE ||
netType == ConnectivityManager.TYPE_WIFI /*||
netType == ConnectivityManager.TYPE_WIMAX ||
netType == ConnectivityManager.TYPE_ETHERNET */ );
}
return connected;
根据 OP 的问题,我将此代码限制为 Wi-Fi 和 3G,但很容易将其扩展到新添加的连接类型,例如以太网或 Wi-Max.
I limited this code to Wi-Fi and 3G as per the OP's question but it's easy to extend it to newly added connection types such as Ethernet or Wi-Max.
这篇关于如何确定Android互联网连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!