【问题标题】:Timeout for check internet connection AndroidAndroid 检查互联网连接超时
【发布时间】:2016-09-16 16:11:52
【问题描述】:

我正在通过 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) 因为它返回一个 boolean 。我该如何解决?

【问题讨论】:

    标签: java android connection ping


    【解决方案1】:

    如果方法没有在分配的时间内完成,有几种方法可以取消它。

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

    【讨论】:

    • 您的代码可以完美地添加相应的异常。有必要转换一个布尔变量结果。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2012-06-12
    • 1970-01-01
    • 2016-08-28
    • 2017-11-30
    • 2012-02-21
    • 2013-02-02
    • 2011-02-14
    • 2012-03-23
    相关资源
    最近更新 更多