我正在开发一个Android应用程序,在我的应用程序中,我想检查网络连接,就像我想检查wifi和3G中的网络连接(如印度人大多喜欢移动中的数据计划),如何检查网络中的wifi和3G.naybody知道,请对此有所了解。
由于
答案 0 :(得分:38)
请试试这个
public static boolean isInternetConnected (Context ctx) {
ConnectivityManager connectivityMgr = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = connectivityMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo mobile = connectivityMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
// Check if wifi or mobile network is available or not. If any of them is
// available or connected then it will return true, otherwise false;
if (wifi != null) {
if (wifi.isConnected()) {
return true;
}
}
if (mobile != null) {
if (mobile.isConnected()) {
return true;
}
}
return false;
}
请在android清单文件中添加以下权限。
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
答案 1 :(得分:9)
这是代码段。如果网络启用则返回true,否则返回false
private boolean netCheckin() {
try {
ConnectivityManager nInfo = (ConnectivityManager) getSystemService(
Context.CONNECTIVITY_SERVICE);
nInfo.getActiveNetworkInfo().isConnectedOrConnecting();
Log.d(tag, "Net avail:"
+ nInfo.getActiveNetworkInfo().isConnectedOrConnecting());
ConnectivityManager cm = (ConnectivityManager) getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
Log.d(tag, "Network available:true");
return true;
} else {
Log.d(tag, "Network available:false");
return false;
}
} catch (Exception e) {
return false;
}
}
答案 2 :(得分:2)
您可以使用以下代码,这适用于所有API版本:
ConnectivityManager cm =
(ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
if(isConnected)
{
if(activeNetwork.getType()==ConnectivityManager.TYPE_MOBILE)
return true;
else
return false;
}
else
return false;
答案 3 :(得分:1)
我在Activity类
中使用这个private boolean isConnectedToInternet() {
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return (networkInfo != null);
}