2016-09-16 25 views
1

Googleにpingを実行してインターネット接続状態を確認しています。問題は、接続がなく、待ち時間が超過拡張されている場合です。インターネット接続をチェックするためのタイムアウトAndroid

これは私のコードです:

private boolean checkInternet() { 
    String netAddress = null; 
    try 
    { 
     netAddress = new NetTask().execute("www.google.com").get(); 
     return (!netAddress.equals("")); 
    } 
    catch (Exception e1) 
    { 
     e1.printStackTrace(); 
     return false; 
    } 
    return false; 
} 

public class NetTask extends AsyncTask<String, Integer, String> 
{ 
    @Override 
    protected String doInBackground(String... params) 
    { 
     InetAddress addr = null; 
     try 
     { 
       addr = InetAddress.getByName(params[0]); 
     } 
     catch (UnknownHostException e) 
     { 
      e.printStackTrace(); 
      return ""; 
     } catch (IOException time) 
     { 
      time.printStackTrace(); 
      return ""; 
     } 
     return addr.getHostAddress(); 
    } 
} 

それはbooleanを返すので、私はisReachable(int timeout)を連結することはできません。それをどうすれば解決できますか?

答えて

0

メソッドが割り当てられた時間内に完了しない場合、メソッドを取り消すにはいくつかの方法があります。

最初の回答to this questionはおそらく私が行く方法です。ここにあなたの例に入れられています。

ExecutorService executor = Executors.newCachedThreadPool(); 
Callable<Object> task = new Callable<Object>() { 
    public Object call() { 
     String netAddress = new NetTask().execute("www.google.com").get(); 
     return (!netAddress.equals("")); 
    } 
}; 
Future<Object> future = executor.submit(task); 
try{ 
    //Give the task 5 seconds to complete 
    //if not it raises a timeout exception 
    Object result = future.get(5, TimeUnit.SECONDS); 
    //finished in time 
    return result; 
}catch (TimeoutException ex){ 
    //Didn't finish in time 
    return false; 
} 
+0

あなたのコードは、対応する例外を完全に追加して動作します。ブール変数の結果をキャストする必要がありました。どうもありがとうございました ! – Mike

関連する問題