繁体   English   中英

超时检查互联网连接Android

[英]Timeout for check internet connection Android

我通过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 我怎么解决这个问题?

如果方法在指定的时间内没有完成,有几种方法可以取消该方法。

这个问题的第一个答案可能是我要去的方式。 这里插入到您的示例中。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM