How to Check Internet Connection in Android with No Internet Connection Dialog? – GeeksforGeeks

Hello geeks, today we are going to learn that how we can add the functionality of Internet Alert to our application. You have definitely seen in almost all applications that when data is turned off or application is not able to get Internet then it pops up a message of “No Internet Connection” and then again it is connected to data is displays message as “Back Online’ or “Internet in connected”, we are going to implement the same in our application. 

Goals/purposes of Internet Alert:

  • To inform the user that he/she is not connected to the network.
  • To stop all internet-related activities or services in the application.

What we are going to build in this article?

Here, we will be creating a button. Whenever the user will press the button message of Internet Connectivity will be displayed. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article.

Step by Step Implementation

Step 1: Creating a new project

  • Open a new project.
  • We will be working on Empty Activity with language as Java. Leave all other options unchanged.
  • You can change the name of the project at your convenience.
  • There will be two default files named activity_main.xml and MainActivity.java.

If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? 

Step 2: Navigate to app > manifests > AndroidManifest.xml file and paste the following piece of code to add internet permission

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

Step 3: Working with activity_main.xml file

We are using a button in the activity_main.xml file to perform the action. Use the following code in the activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>

  

<RelativeLayout 

    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity">

  

    

    <Button

        android:id="@+id/btn_check"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerInParent="true"

        android:text="Check Internet Connection" />

  

</RelativeLayout>



After implementing the above code, the design of the activity_main.xml file will look like this.

Step 4: Working with java files

Create a new java class named as ConnectionReceiver using the following method   

Use the below code in the ConnectionReceiver.java file.

Java




import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.net.ConnectivityManager;

import android.net.NetworkInfo;

  

public class ConnectionReceiver extends BroadcastReceiver {

  

    

    public static ReceiverListener Listener;

  

    @Override

    public void onReceive(Context context, Intent intent) {

  

        

        ConnectivityManager connectivityManager = (ConnectivityManager)

                context.getSystemService(Context.CONNECTIVITY_SERVICE);

          

        

        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

          

        

        if (Listener != null) {

              

            

            

            

            boolean isConnected = networkInfo != null && networkInfo.isConnectedOrConnecting();

              

            

            Listener.onNetworkChange(isConnected);

        }

    }

  

    public interface ReceiverListener {

        

        void onNetworkChange(boolean isConnected);

    }

}



Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.content.Context;

import android.content.IntentFilter;

import android.graphics.Color;

import android.net.ConnectivityManager;

import android.net.NetworkInfo;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.TextView;

  

import androidx.appcompat.app.AppCompatActivity;

  

import com.google.android.material.snackbar.Snackbar;

  

public class MainActivity extends AppCompatActivity implements ConnectionReceiver.ReceiverListener {

  

    Button btn_check;

  

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

  

        

        btn_check = findViewById(R.id.btn_check);

  

        

        checkConnection();

        btn_check.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View view) {

                

                checkConnection();

            }

        });

    }

  

    private void checkConnection() {

  

        

        IntentFilter intentFilter = new IntentFilter();

  

        

        intentFilter.addAction("android.new.conn.CONNECTIVITY_CHANGE");

  

        

        registerReceiver(new ConnectionReceiver(), intentFilter);

  

        

        ConnectionReceiver.Listener = this;

  

        

        ConnectivityManager manager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);

  

        

        NetworkInfo networkInfo = manager.getActiveNetworkInfo();

  

        

        boolean isConnected = networkInfo != null && networkInfo.isConnectedOrConnecting();

  

        

        showSnackBar(isConnected);

    }

  

    private void showSnackBar(boolean isConnected) {

  

        

        String message;

        int color;

  

        

        if (isConnected) {

              

            

            

            message = "Connected to Internet";

              

            

            color = Color.WHITE;

  

        } else {

              

            

            

            

            message = "Not Connected to Internet";

              

            

            color = Color.RED;

        }

  

        

        Snackbar snackbar = Snackbar.make(findViewById(R.id.btn_check), message, Snackbar.LENGTH_LONG);

          

        

        View view = snackbar.getView();

          

        

        TextView textView = view.findViewById(R.id.snackbar_text);

          

        

        textView.setTextColor(color);

          

        

        snackbar.show();

    }

  

    @Override

    public void onNetworkChange(boolean isConnected) {

        

        showSnackBar(isConnected);

    }

  

    @Override

    protected void onResume() {

        super.onResume();

        

        checkConnection();

    }

  

    @Override

    protected void onPause() {

        super.onPause();

        

        checkConnection();

    }

}



Congratulations! we have successfully made the application to check Internet Connection and alert it to the user. Here is the final output of our application.

Output:

My Personal Notes

arrow_drop_up