Android Tutorials

How to Check Internet Connection in Android App (For Developers)

Hello guys, from today, I will be posting android related coding tutorials for some of the most googled questions so that you can continue creating your app easily and spend less time searching for the answer to your question on Internet.

Today we will see how can we check if Internet Connection is present in an android phone or not. 

Step 1. Let us first create an xml(activity_main.xml) which we shall use to show the result if connection is present or not

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="guru.randomblog.internetconnection.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""
        android:id="@+id/tv"
        android:textSize="25dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Step 2. Create a java file with name ConnectionDetector.java

Then we shall use a stand alone Connection Detector class to check the presence of Internet. The reason for using this is you can just call this class in part of your application and check if internet is connected or not. This will reduce your time for writing same code in the same app if you want to check in multiple parts of your app.

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectionDetector {

    private Context _context;

    public ConnectionDetector(Context context){
        this._context = context;
    }

    public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null)
        {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }

        }
        return false;
    }
}

The ConnectionDetector class will return true or false values based on whether internet connection is present or no.

Step 3: Then, create the MainActivity.java if you haven’t and paste the following code.

Create a boolean value isInternetPresent and create an instance of ConnectionDetector with name cd. When we query cd.isConnectingToInternet() we will get back the result as true or false. We can then use that result to perform any of the tasks required. Here in this app, we will show the result in a TextView using setText function.

public class MainActivity extends AppCompatActivity {
    // flag for Internet connection status
    Boolean isInternetPresent = false;
    // Connection detector class
    ConnectionDetector cd;
    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView) findViewById(R.id.tv);
        cd = new ConnectionDetector(getApplicationContext());
        isInternetPresent = cd.isConnectingToInternet();
        if (isInternetPresent) {
            tv.setText("Internet is Present");
            Toast.makeText(getApplicationContext(), "Connected to Internet!", Toast.LENGTH_SHORT).show();
        } else {
            tv.setText("Internet is Not Present");
            Toast.makeText(getApplicationContext(), "No Connection found!", Toast.LENGTH_SHORT).show();

        }
    }
}

Step 4. Next step is to give permissions to the app to access Internet and network access.

Remember without giving these permissions, your app will force close.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="guru.randomblog.internetconnection">
    //Give Internet Permission
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Now, run the application on your emulator or your mobile phone and check the result.

Internet Present in android

Internet Present 

Not connected to internet

No connection found

Whenever in your app if  you want to check if the phone is connected to internet, you can just call the below function:


ConnectionDetector cd;
boolean isConnected = cd.isConnectingToInternet();

That’s all folks. Easy isn’t it. Just create the ConnectionDetector.java and call the function isConnctedtoInternet(). If you have any issues comment below, we can resolve it.

If this post helped you, please like our Facebook page. 🙂

Download all the files of this tutorial below:

Download Full Code

About the author

Darshan Gowda

Follow me on Facebook, Google Plus

Leave a Comment

error: Content is protected !!