如何验证INTERNET的android活动存在

时间:2017-02-21 15:27:04

标签: android

当wifi关闭且移动网络关闭时我可以检测到它,但是当两者都打开时,即使没有网络,我的验证也不起作用。现在我需要知道当移动数据和WIFI打开或关闭时我如何验证INTERNET的缺失。

我的代码:

NetworkInfo nf;


 ConnectivityManager cn=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    nf=cn.getActiveNetworkInfo();

             if(nf != null && nf.isConnected()==true )  
             {

        //    switch to new activity
             }

2 个答案:

答案 0 :(得分:0)

您可以尝试ping google.com以验证您的连接。您在此处有Stack Overflow主题:How to Ping External IP from Java Android

答案 1 :(得分:0)

我正在使用它,到目前为止工作正常

   public static boolean isOnline() {
        InetAddress inetAddress = null;
        try {
            Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() {
                @Override
                public InetAddress call() {
                    try {
                        return InetAddress.getByName("google.com");
                    } catch (UnknownHostException e) {
                        return null;
                    }
                }
            });
            inetAddress = future.get(2000, TimeUnit.MILLISECONDS);
            future.cancel(true);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
        return inetAddress != null && !inetAddress.equals("");
    }

您可以将其放在NetworkUtil类中,并使用静态方法检查连接性。