【发布时间】:2015-03-31 05:58:33
【问题描述】:
我尝试编写一个安卓程序来使用两种不同的方法检查互联网连接。第一种是最常用的方法,CheckInternetConnection(),第二种方法是通过连接到一个网站,ConnectGoogleTest()。 第一个工作完美,但在第二个中我的平板电脑挂了!有人知道为什么吗?
代码是:
public class myITClass {
private Context ctx ;
public myITClass(Context context){
this.ctx = context;
}
public boolean CheckInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
//NetworkInfo ni = cm.getActiveNetworkInfo();
if (cm.getActiveNetworkInfo() == null) {
// There are no active networks.
return false;
} else {
return true;
}
}
public boolean googlePingTest(){
boolean res = false ;
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(15000);
urlc.connect();
if (urlc.getResponseCode() == 200) { res = true; }
} catch (MalformedURLException e1) {
res = false;
} catch (IOException e) {
res = false ;
}catch (Exception e){
res = false ;
}
return res;
}
}
【问题讨论】:
-
我不认为你可以设置连接超时之后调用
openConnection()。 logcat 中的任何内容? -
我在这里回答了同样的问题,并且工作正常。唯一不同的是为连接设置了几个属性。 stackoverflow.com/questions/27988103/…
标签: android connection httpconnection