- Implementing Internet Connectivity Checker in Android Apps
- Enough talk!
- Back to our business
- That’s it!
- Android Detect Internet Connection Status
- Creating New Project
- Broadcasting Internet Status to All Activities
- Related Posts
- Android Integrating PayTM Payment Gateway – ECommerce App
- Android Integrating Google’s reCAPTCHA in your App
- Android Content Placeholder Animation like Facebook using Shimmer
- Android Detect Internet Connection Status
- Creating New Project
- Broadcasting Internet Status to All Activities
- Related Posts
- Android Integrating PayTM Payment Gateway – ECommerce App
- Android Integrating Google’s reCAPTCHA in your App
- Android Content Placeholder Animation like Facebook using Shimmer
Implementing Internet Connectivity Checker in Android Apps
Dec 31, 2020 · 4 min read
W orking on an Android chat app? social media app? or any other internet-based app that you want to check if there is an internet connection in order to continue a process or even notify the user about their network state? This guide comes to the rescue!
You may say: “ Hey! There is already an API which gets this job done.”
Yes, there is! Well, although Android SD K provides API that you can use to get network state of user’s device like ConnectivityManager, it does not actually check whether there is an active internet connection. Concretely, try establishing a hotspot from mobile device “A” but do not turn on mobile data or WiFi, then connect mobile device “B” to that hotspot of “A”.
Using device “B”, when you try to search, say, on Google this won’t work as there is no internet connection although you are connected to a network. ConnectivityManager APIs work the same. They just tell whether you are connected to a network or not — regardless of having an active internet connection or not.
So, the bottom line is:
“How do we check if there is an active internet connection?”
Basically, we can ping or connect to any server to see whether this ping or connection is successful or not.
If you have your own back-end server, you may prefer to try to connect your app to the server to make sure that the device has an internet connection and your server is not down at the same time.
We can also connect to Google’s servers as they are unlikely to be down (or for a long time).
To optimize our class implementation (we’ll call it NetworkConnectivity), it’s good to check a device’s network connection using ConnectivityManager so that if WiFi or mobile data is turned off or even WiFi is turned on but there is no network the device is connected to, we don’t have to make requests to any servers.
Enough talk!
First of all, add internet and network state permissions in your app manifest:
Now, create a function to check network availability using ConnectivityManager:
Here we used getAllNetworkInfo() to return an array of objects of all networks and then we check whether any of them is connected.
But this method is deprecated since API 23. For later APIs, we used getAllNetworks() which is added in API 21. But yea, getNetworkInfo() is also deprecated since API 29 🙂
Back to our business
To ping Google’s server, basically, we can do that with a few lines of code:
This approach works synchronously so that you just wait for the response to tell whether you have a connection or not and it takes no time. However, in some mobile devices for specific brands, the framework does not allow performing this process in Runtime, so you can not eventually rely on it.
Instead, we can make a normal HTTP connection request to the server.
Start by creating a method called checkInternetConnection which checks first if WiFi or mobile data are connected to any network by using the above method. Then it starts establishing an HTTP URL connection:
ConnectivityCallback is an inner interface having an abstract function which we’ll use to communicate with our UI classes when the server’s response comes back.
In the above checkInternetConnection function we used: “ http://clients3.google.com/generate_204” instead of Google’s normal URL “ http://www.google.com” since the first is a bit more efficient so that we don’t have to grab the whole web page.
For a successful request, the response code must be equals to 204 and no content is returned back.
We used “ setRequestProperty()” to set headers (some information the server needs to know) for the request for the server. Also, we specified the connection timeout to be one second which is a reasonable time.
But wait! Android framework does not allow network operations on the main thread so we need to use the above code on another thread. Consequently, we’ll have to post the result on the main thread again. You can use whatever is convenience for you to perform both of these operations. I would use a singleton AppExecutors class which provides executor threads for both of our cases.
postCallback() is a helper method that posts our result to the interface on the main thread.
That’s it!
To check internet connectivity in an activity:
In recent devices, Android may produce a security exception due to using HTTP URL connection. To fix this, add android:usesCleartextTraffic=”true” in your app manifest within application tag or use HTTPS instead of HTTP connections. So, pay attention to exception handling in your checkInternetConnection method.
Источник
Android Detect Internet Connection Status
Detecting internet connection status in your app is very easy and won’t take more than 5mins. In this article you will learn how to detect internet connection status manually and automatically. Using broadcast receiver, your app will be automatically notified when there is a change in network connection.
This provides easy way do any changes in the app like hiding few button (like WhatsApp hides send, upload icon when there is not internet), navigation user to another screen, or just show a Snackbar message.
VIDEO DEMO
Creating New Project
1. Create a new project in Android Studio from File ⇒ New Project. When it prompts you to select the default activity, select Blank Activity and proceed.
2. Create a class named ConnectivityReceiver.java and extend it from BroadcastReceiver. This is a receiver class which will be notified whenever there is change in network / internet connection.
3. Create another class named MyApplication.java and extend it from Application. This class will be called whenever app is launched. Here setConnectivityListener() method is used to initiate the connectivity listener.
4. Open AndroidManifest.xml and do the below changes.
> Add MyApplication to tag.
> Add ConnectivityReceiver as .
> Declare INTERNET and ACCESS_NETWORK_STATE permissions.
Broadcasting Internet Status to All Activities
Now we have all the setup ready. Let’s see how to notify an activity when the device is connected or disconnected from internet.
5. Open layout file main activity activity_main.xml add the below layout.
6. Open your MainActivity.java and do the below changes to receive the internet status.
> Register the connection change listener in onResume() method by calling MyApplication.getInstance().setConnectivityListener(this).
> Implement the activity from ConnectivityReceiver.ConnectivityReceiverListener which will override onNetworkConnectionChanged() method.
> onNetworkConnectionChanged() method will be triggered whenever device is connected / disconnected from internet. You need to take appropriate action here.
Follow the above same three steps in all other activities in which in you want to notify the internet status.
Run the project and try turning off / on wifi or mobile data. You can notice a Snackbar is shown with network connection status.
Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: [email protected]
Related Posts
Android Integrating PayTM Payment Gateway – ECommerce App
Android Integrating Google’s reCAPTCHA in your App
Android Content Placeholder Animation like Facebook using Shimmer
Due non-availability of Internet, I get fail message , need to store the data locally it as soon as valid internet connectivity is available then send data.How will i do it?
I tried your connectiondetector code but its returning true always and not going to else loop.could u please sort out the problem.i used your code as it is.
its done now.actully the problem was from my side.i did not disabled my device internet connection instead it i was disabling it in my system.thanks a lot for such a nice tutorial
thanks, this tutorial is very helpful…
very helpful, thanks
hi ravi
i have aquestion, if u can help me im so thankful. i have an app that need access to internet in some activity but when the net speed is low all my activities run slowly .when i delete permission it works fine .what can i do :(( help me
Very nice and Simple tutorial. Thanks
I want to know i want to use without refreshing , how to validate internet connection meaning auto check internet connection.
ok men!! ok excelent! yeah
nice english, hihi
This is not giving correct response when im connected to the wifi which is not connected to the internet.
Excellent tutorial…Thanks ravi..
Nice tutorials. but it check only data enable or not in internal setting only,, not externally. that means when i transfer the data in host side it check the network status in that time
ConnectionDetector needs a return type to compile (I inserted “void”).
No, It doesn’t show. It only checks ON or OFF not for active state.
Thanks, this was a nice little tutorial and added a much needed notification to my app 🙂
this only works when you are connected to any network, but doesn’t work when you want to know if that network has internet connection
dude,Its check status only… but some time internet connected but no internet access…
Dude when ever i check it only returns true value.When i dont have internet then also it returns you have internet .
this is the best android tutorial website I’ve ever visited.. THANKS..
when we connected wifi even there is limited network. it shows internet is connected
I have a question regarding the process Android uses to determine internet connection. The case is this.
We have an Android USB stick that does not set the correct date/time when it starts. When we connect it to internet and set auto date/time, it is correctly synced at startup, and the network connection states that there is internet, and the name of the wifi or wired network.
Now, when we place a router in the wifi network configuration, the Android player states that there is no internet connection and the date/time is not set. However, browsing pages through a browser (Chrome) works fine, and so do RSS feeds. Syncing date/time does not work, although all NTP ports in the router have been opened. When we drop all access lists in the router, syncing works fine, so it must be one of these access rules, but there are too many to find the correct one.
Since Android states that there is no internet connection but browsing pages works fine, I assume that at startup, Android signals some (Google) URL to determine whether there is internet connection (most likely some functionality in the isConnectingToInternet() functionality in this tutorial), and that this particular signal is blocked for security reasons. Am I correct that if at startup Android determines that there is no internet connection, it stops any other functionality to attempt to work, since it flagged no internet to be available?
Does anyone here know what steps Android takes exactly to determine internet availability? What URL or port or combination of these that may be blocked by some routers?
Источник
Android Detect Internet Connection Status
Detecting internet connection status in your app is very easy and won’t take more than 5mins. In this article you will learn how to detect internet connection status manually and automatically. Using broadcast receiver, your app will be automatically notified when there is a change in network connection.
This provides easy way do any changes in the app like hiding few button (like WhatsApp hides send, upload icon when there is not internet), navigation user to another screen, or just show a Snackbar message.
VIDEO DEMO
Creating New Project
1. Create a new project in Android Studio from File ⇒ New Project. When it prompts you to select the default activity, select Blank Activity and proceed.
2. Create a class named ConnectivityReceiver.java and extend it from BroadcastReceiver. This is a receiver class which will be notified whenever there is change in network / internet connection.
3. Create another class named MyApplication.java and extend it from Application. This class will be called whenever app is launched. Here setConnectivityListener() method is used to initiate the connectivity listener.
4. Open AndroidManifest.xml and do the below changes.
> Add MyApplication to tag.
> Add ConnectivityReceiver as .
> Declare INTERNET and ACCESS_NETWORK_STATE permissions.
Broadcasting Internet Status to All Activities
Now we have all the setup ready. Let’s see how to notify an activity when the device is connected or disconnected from internet.
5. Open layout file main activity activity_main.xml add the below layout.
6. Open your MainActivity.java and do the below changes to receive the internet status.
> Register the connection change listener in onResume() method by calling MyApplication.getInstance().setConnectivityListener(this).
> Implement the activity from ConnectivityReceiver.ConnectivityReceiverListener which will override onNetworkConnectionChanged() method.
> onNetworkConnectionChanged() method will be triggered whenever device is connected / disconnected from internet. You need to take appropriate action here.
Follow the above same three steps in all other activities in which in you want to notify the internet status.
Run the project and try turning off / on wifi or mobile data. You can notice a Snackbar is shown with network connection status.
Hi there! I am Founder at androidhive and programming enthusiast. My skills includes Android, iOS, PHP, Ruby on Rails and lot more. If you have any idea that you would want me to develop? Let’s talk: [email protected]
Related Posts
Android Integrating PayTM Payment Gateway – ECommerce App
Android Integrating Google’s reCAPTCHA in your App
Android Content Placeholder Animation like Facebook using Shimmer
Due non-availability of Internet, I get fail message , need to store the data locally it as soon as valid internet connectivity is available then send data.How will i do it?
I tried your connectiondetector code but its returning true always and not going to else loop.could u please sort out the problem.i used your code as it is.
its done now.actully the problem was from my side.i did not disabled my device internet connection instead it i was disabling it in my system.thanks a lot for such a nice tutorial
thanks, this tutorial is very helpful…
very helpful, thanks
hi ravi
i have aquestion, if u can help me im so thankful. i have an app that need access to internet in some activity but when the net speed is low all my activities run slowly .when i delete permission it works fine .what can i do :(( help me
Very nice and Simple tutorial. Thanks
I want to know i want to use without refreshing , how to validate internet connection meaning auto check internet connection.
ok men!! ok excelent! yeah
nice english, hihi
This is not giving correct response when im connected to the wifi which is not connected to the internet.
Excellent tutorial…Thanks ravi..
Nice tutorials. but it check only data enable or not in internal setting only,, not externally. that means when i transfer the data in host side it check the network status in that time
ConnectionDetector needs a return type to compile (I inserted “void”).
No, It doesn’t show. It only checks ON or OFF not for active state.
Thanks, this was a nice little tutorial and added a much needed notification to my app 🙂
this only works when you are connected to any network, but doesn’t work when you want to know if that network has internet connection
dude,Its check status only… but some time internet connected but no internet access…
Dude when ever i check it only returns true value.When i dont have internet then also it returns you have internet .
this is the best android tutorial website I’ve ever visited.. THANKS..
when we connected wifi even there is limited network. it shows internet is connected
I have a question regarding the process Android uses to determine internet connection. The case is this.
We have an Android USB stick that does not set the correct date/time when it starts. When we connect it to internet and set auto date/time, it is correctly synced at startup, and the network connection states that there is internet, and the name of the wifi or wired network.
Now, when we place a router in the wifi network configuration, the Android player states that there is no internet connection and the date/time is not set. However, browsing pages through a browser (Chrome) works fine, and so do RSS feeds. Syncing date/time does not work, although all NTP ports in the router have been opened. When we drop all access lists in the router, syncing works fine, so it must be one of these access rules, but there are too many to find the correct one.
Since Android states that there is no internet connection but browsing pages works fine, I assume that at startup, Android signals some (Google) URL to determine whether there is internet connection (most likely some functionality in the isConnectingToInternet() functionality in this tutorial), and that this particular signal is blocked for security reasons. Am I correct that if at startup Android determines that there is no internet connection, it stops any other functionality to attempt to work, since it flagged no internet to be available?
Does anyone here know what steps Android takes exactly to determine internet availability? What URL or port or combination of these that may be blocked by some routers?
Источник