超时检查互联网连接Android

时间:2016-09-16 16:11:52

标签: java android connection ping

我通过ping谷歌检查互联网连接状态。问题是,当没有连接且等待时间过长时。

这是我的代码:

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();
    }
}

我无法连接isReachable(int timeout)因为它返回boolean。我该如何解决?

1 个答案:

答案 0 :(得分: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;
}