我已經編寫了一些代碼來ping Google以檢查Internet連接。Android - 使用ping檢查互聯網連接的大量綁定
該應用程序的工作原理除了需要大量時間發送迴應(最多1分鐘)之外。這種情況尤其是當移動網絡已打開,但沒有互聯網連接
我將不勝感激,如果你能幫助我找到一個解決方案
佈局由只是一個按鈕的。 以下是我的Java代碼:
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();
}
}
}
謝謝。
PLZ給我修改我的代碼,謝謝你提前 –
http://stackoverflow.com/questions/39408697/what-is-the-solution-to-check-internet-connectivity/39408778#39408778 – kgandroid
什麼時間是'非常大的時間' –