我正在使用这些代码AsyncTask检查Internet连接:
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
//toast show
}
Run Code Online (Sandbox Code Playgroud)
此代码不适用于大多数华为型号和三星Galaxy Note 3等设备.
此外,如果用户与GPRS,EDGE,3G,4G等数据进行互联网连接...
在所有设备和所有类型的连接上检查互联网连接以支持的最佳代码是什么?
android ×1