由网友(喂,放开那帅比)分享简介:在这里,我的Android设备同时支持WiFi和3G。在特定时间的网络可在此设备上。因为我的要求是,当3G是可用我要上传少量数据。当无线可用整个数据必须上传。所以,我要检查连接WiFi或3G。请帮我。提前致谢。 Here, my android device supports both wifi and 3g....
在这里,我的Android设备同时支持WiFi和3G。在特定时间的网络可在此设备上。因为我的要求是,当3G是可用我要上传少量数据。当无线可用整个数据必须上传。所以,我要检查连接WiFi或3G。请帮我。提前致谢。
Here, my android device supports both wifi and 3g. At particular time which network is available on this device. Because my requirement is when 3g is available I have to upload small amount of data. when wifi is available entire data have to upload. So, I have to check connection is wifi or 3g. Please help me. Thanks in advance.
推荐答案
我用这样的:
/**
* Checks if we have a valid Internet Connection on the device.
* @param ctx
* @return True if device has internet
*
* Code from: http://www.androidsnippets.org/snippets/131/
*/
public static boolean haveInternet(Context ctx) {
NetworkInfo info = (NetworkInfo) ((ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info == null || !info.isConnected()) {
return false;
}
if (info.isRoaming()) {
// here is the roaming option you can change it if you want to
// disable internet while roaming, just return false
return false;
}
return true;
}
您还需要
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
在AndroidMainfest.xml
in AndroidMainfest.xml
为了让您可以使用此code段的网络类型:
ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//mobile
State mobile = conMan.getNetworkInfo(0).getState();
//wifi
State wifi = conMan.getNetworkInfo(1).getState();
,然后用它这样的:
and then use it like that:
if (mobile == NetworkInfo.State.CONNECTED || mobile == NetworkInfo.State.CONNECTING) {
//mobile
} else if (wifi == NetworkInfo.State.CONNECTED || wifi == NetworkInfo.State.CONNECTING) {
//wifi
}
要获得移动网络我会尝试TelephonyManager#getNetworkType或NetworkInfo#getSubtypeName
To get the type of the mobile network I would try TelephonyManager#getNetworkType or NetworkInfo#getSubtypeName
相关推荐
最新文章