How to check if the Internet connection (Wifi / Mobile data) is connected?

How to check if internet connection is enabled on Android? For example, if the LOCATION SERVICE service is disabled, we use the technique

Location myLocation = locationmanager.getLastKnownLocation(provider); if(myLocation == null){ Show the AlertDialog. }else{ do this. } 

How is it, how can I check if the Internet connection is on / off.

0
source share
2 answers

You can use the following method:

 ConnectivityManager conectivtyManager = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE); if (conectivtyManager.getActiveNetworkInfo() != null && conectivtyManager.getActiveNetworkInfo().isAvailable() && conectivtyManager.getActiveNetworkInfo().isConnected()) { isConnected = true; } else { isConnected= false; } 

Hope this helps!

+2
source

For wifi:

 ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI); connected = networkInfo != null && networkInfo.isConnected(); 

For mobile devices:

 ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = mgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); connected = networkInfo != null && networkInfo.isConnected(); 
+2
source

Source: https://habr.com/ru/post/1239243/


All Articles