Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Check Network Reachability(Network Availability) in Android using few lines of code

Network Reachability, Network Availability, Internet Connection Checking
Hello Friends,

- In this post i am going to show how we can check "Network Reachability" in Android using simple code.
- We can use this code in our app while calling API or other network related stuffs.
STEP : 1

Add some important permissions in AndroidManifiest.xml file.

uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
uses-permission android:name="android.permission.INTERNET" />
uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

STEP : 2
Create function which checks whether internet connection is available in device or not?

public static boolean hasConnection(Context context) {
ConnectivityManager cm = (ConnectivityManager)
                             context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null) { // connected to the internet if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { // connected to wifi return true; } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { // connected to the mobile provider's data plan return true; } } else return false; return false; }

- Finally you can call this method before doing network related task like calling API or downloading/uploading something to server.
- If this method return true then do network operation else show network error to user.

Happy Coding ;)

Share the post

Check Network Reachability(Network Availability) in Android using few lines of code

×

Subscribe to Android Blog - Latest Android And Kotlin Development News And Tips To Help You Grow Your Programing

Get updates delivered right to your inbox!

Thank you for your subscription

×