Checking your network and Internet connection - Android

I was wondering if the method below checks that I am both connected to the network and can actually connect to the Internet.

Not just connected to a network that won't let me access the Internet?

public boolean isNetworkAvailable() { ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getActiveNetworkInfo(); boolean isAvailable = false; if (networkInfo != null && networkInfo.isConnected()) { isAvailable = true; } return isAvailable; } 

I think so, but I'm not 100% sure.

thanks

+6
source share
4 answers

When comparing the accepted answer to this post with your code, what you are doing should work. Feel free to compare the code. The safest thing to do would be to run some tests from airplane mode, with WiFi turned off and from a location away from WiFi, to be sure. Good luck.

Android - programmatically check your internet connection and display dialog if not connected

+2
source

Check out one of my old answers . It has two different methods: 1. Check if the device is connected to the network 2. Check if the device is connected to the Internet.

+2
source

The code below checks the internet connection using kotlin in android studio:

 private fun amIConnected(): Boolean { val connectivityManager = this.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager val activeNetworkInfo = connectivityManager.activeNetworkInfo return activeNetworkInfo != null && activeNetworkInfo.isConnected } 
0
source

I tried the user approach : 3156908 , but he continued to destroy my application when the Internet connection was disconnected. It turns out that there was a logical error in his code, so I used connectivityManager.getActiveNetworkInfo() != null to check the network details. If the device is connected to a network or is in the process of connecting to a network, use isConnectedOrConnecting()

In your AndroidManifest.xml file add the following

 <!-- Internet Permissions --> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 

Create a method called checkInternetConnection in your fragment class or activity class and add the following lines of code.

  @TargetApi(Build.VERSION_CODES.LOLLIPOP) private boolean checkInternetConnection(){ ConnectivityManager connectivityManager = (ConnectivityManager) mcontext.getSystemService(mcontext.CONNECTIVITY_SERVICE); return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnectedOrConnecting(); } 

You can then call the checkInternetConnection method in your onViewCreated or your onCreate activity onCreate .

Note I strongly recommend that you check the code when it is connected to Wi-Fi, mobile data, and flight mode.

0
source

All Articles