我想检查WiFi或移动数据连接是否(能够检查)但是能否访问互联网
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
public static boolean isInternetAccessible(Context context) {
if (isNetworkAvailable(context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://aapapps.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e("LOG_TAG", "Couldn't check internet connection", e);
}
} else {
Log.d("LOG_TAG", "Internet not available!");
}
return false;
}
答案 0 :(得分:3)
尝试其工作代码
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
答案 1 :(得分:0)
检查以下代码,您必须在清单文件中添加Internet访问权限。如果isInternetConnectionAvailable()返回true,那么您的设备可以访问互联网,否则它无法连接到互联网。
<uses-permission android:name="android.permission.INTERNET" />
public boolean isInternetConnectionAvailable() {
ConnectivityManager connectivity = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo networkInfo = connectivity.getActiveNetworkInfo();//active network information
if (networkInfo != null) {
return networkInfo.isConnected();
}
}
return false;
}
如果您需要所有网络信息,请使用以下代码。
NetworkInfo[] info = connectivity.getAllNetworkInfo();
答案 2 :(得分:0)
在检查设备是否通过WiFi或移动数据连接后,为什么不只是ping Google或任何其他最有可能始终可用的网络应用程序?
如果您收到有效回复,则可以访问互联网。