检查互联网连接超时 Android

Timeout for check internet connection Android

我正在通过 ping google 检查 Internet 连接状态。问题是,当没有连接并且等待时间超长时。

这是我的代码:

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) 因为它 returns 一个 boolean 。我该如何解决?

如果某个方法没有在规定的时间内完成,有几种方法可以取消它。

第一个答案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;
}