Android-使用ping检查Internet连接是否需要花费大量精力 [英] Android - Large amount of tie taken to check Internet connectivity using ping
本文介绍了Android-使用ping检查Internet连接是否需要花费大量精力的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经写了一些代码ping Google来检查Internet连接.
I have written some code to ping Google to check Internet connectivity.
该应用程序可以正常工作,只是它需要花费很多时间来发回响应(最多1分钟).尤其是在打开移动网络但没有Internet连接的情况下,会发生这种情况
The app works except that it takes a lot of time to send back the response (up-to 1 min). This happens especially when Mobile Network is turned ON but there is no Internet connectivity
如果您能帮助我找到解决方法,我将不胜感激
I would appreciate it if you would help me find a solution
布局仅包含一个按钮. 以下是我的Java代码:
The layout consists of just a Button. Following is my Java code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity_final);
Button b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//Thread t = new Thread(new Runnable() {
// public void run() {
//pingCheck = isURLReachable(getApplicationContext());
new MyTask().execute();
//}
//});
//t.start();
}
});
}
private class MyTask extends AsyncTask<Void, Void, Boolean> {
@Override
protected void onPreExecute() {
}
@Override
protected Boolean doInBackground(Void... params) {
try {
URL url = new URL("http://google.com"); // Change to "http://google.com" for www test.
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(10*500); // 10 s.
urlc.connect();
if (urlc.getResponseCode() == 200) { // 200 = "OK" code (http connection is fine).
Log.wtf("Connection", "Success !");
return true;
} else {
return false;
}
} catch (MalformedURLException e1) {
return false;
} catch (IOException e) {
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
boolean bResponse = result;
if (bResponse==true) {
Toast.makeText(MainActivityFinal.this, "Network is available", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivityFinal.this, "Network is not available", Toast.LENGTH_LONG).show();
}
}
}
谢谢.
推荐答案
我建议在urlc.setConnectTimeout(10*500);
下面添加urlc.setReadTimeout(10*500);
.
顺便说一下,这是5秒而不是10秒的超时.
By the way, it's a timeout of 5 seconds and not ten.
这篇关于Android-使用ping检查Internet连接是否需要花费大量精力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文