简体   繁体   中英

Timeout for check internet connection Android

I'm checking Internet connection state by pinging google. The problem is, when there is no connection and the waiting time is hyper-extended.

This is my code:

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

I can not concatenate isReachable(int timeout) because it returns a boolean . How can I solve that?

There are a couple of ways to cancel a method if it doesn't complete in the allotted time.

The first answer to this question is probably the way I would go. Here it is slotted into your example.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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