简体   繁体   English

android:如何检测网络是否已连接到互联网

[英]android:how to detect network is connected to internet

I have this code to check for internet connection. 我有此代码来检查互联网连接。

NetworkInfo info = ((ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();

             //if network is active and have internet connection 
            if(info != null && info.isConnected()==true){


            //Some code


            }

     //if network is inactive or doesn't  have internet connection 
     else   if(info == null || info.isConnected()==false){

               Context context = getApplicationContext();
               CharSequence text = " Bad internet connection.";
               int duration = Toast.LENGTH_LONG;
               Toast toast = Toast.makeText(context, text, duration);
               toast.show();

             }

When I start the program,everything works properly with turn on internet connection,but when I pull out the internet cable from my router and in my app still have turn on wifi the app get true with this (if(info != null && info.isConnected()==true)) and crash.I don't know why this code get true. 当我启动程序时,打开互联网连接一切正常,但是当我从路由器拔出互联网电缆,并且在我的应用程序中仍然打开wifi时,应用程序就可以做到这一点(if(info!= null && info .isConnected()== true))并崩溃。我不知道为什么这段代码为true。

Use this for check condition of network:

if (info!=null && info.isAvailable() && info.isConnected()) {
            return true;
        } else {
            return false; 
        }
}

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

相关问题 如何在Android中检查移动网络是否连接到互联网 - How to check if mobile network is connected to the internet or not in android 如何在Android中检测热点网络上的Internet连接 - How to detect internet Connectivity on hotspot network in android 检测Android设备是否连接到互联网 - Detect if android device is connected to the internet 如何在Android中检测连接在同一wifi网络中的打印机 - How to detect printer connected in same wifi network in android 如何从 Android 应用程序检测 WiFi 网络中连接的所有设备 - How to detect all the Devices connected in a WiFi network from Android App 通过android java检测网络上连接的计算机 - Detect computers connected on network via android java 如何检测WIFI何时连接到互联网? - How to detect when WIFI is connected to internet? 如何显示未在Android中连接的互联网 - How to show internet not connected in android 如何检测连接到wif网络的设备 - How detect the devices connected to wif network 当支持 Internet 的 WiFi 网络可用时,如何使 Android 连接到无法访问 Internet 的 IoT WiFi AP? - How do I keep Android connected to an IoT WiFi AP with no internet access when an internet-enabled WiFi network is available?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM