Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaHow to Check Internet Connection in Android with No Internet Connection Dialog?

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

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"?>
  
<!-- Relative layout as parent layout-->
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <!-- Button to perform the action of Internet alert-->
    <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 {
  
    // initialize listener
    public static ReceiverListener Listener;
  
    @Override
    public void onReceive(Context context, Intent intent) {
  
        // initialize connectivity manager
        ConnectivityManager connectivityManager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
          
        // Initialize network info
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
          
        // check condition
        if (Listener != null) {
              
            // when connectivity receiver
            // listener  not null
            // get connection status
            boolean isConnected = networkInfo != null && networkInfo.isConnectedOrConnecting();
              
            // call listener method
            Listener.onNetworkChange(isConnected);
        }
    }
  
    public interface ReceiverListener {
        // create method
        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);
  
        // assign variable
        btn_check = findViewById(R.id.btn_check);
  
        // create method
        checkConnection();
        btn_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // call method
                checkConnection();
            }
        });
    }
  
    private void checkConnection() {
  
        // initialize intent filter
        IntentFilter intentFilter = new IntentFilter();
  
        // add action
        intentFilter.addAction("android.new.conn.CONNECTIVITY_CHANGE");
  
        // register receiver
        registerReceiver(new ConnectionReceiver(), intentFilter);
  
        // Initialize listener
        ConnectionReceiver.Listener = this;
  
        // Initialize connectivity manager
        ConnectivityManager manager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
  
        // Initialize network info
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
  
        // get connection status
        boolean isConnected = networkInfo != null && networkInfo.isConnectedOrConnecting();
  
        // display snack bar
        showSnackBar(isConnected);
    }
  
    private void showSnackBar(boolean isConnected) {
  
        // initialize color and message
        String message;
        int color;
  
        // check condition
        if (isConnected) {
              
            // when internet is connected
            // set message
            message = "Connected to Internet";
              
            // set text color
            color = Color.WHITE;
  
        } else {
              
            // when internet 
            // is disconnected
            // set message
            message = "Not Connected to Internet";
              
            // set text color
            color = Color.RED;
        }
  
        // initialize snack bar
        Snackbar snackbar = Snackbar.make(findViewById(R.id.btn_check), message, Snackbar.LENGTH_LONG);
          
        // initialize view
        View view = snackbar.getView();
          
        // Assign variable
        TextView textView = view.findViewById(R.id.snackbar_text);
          
        // set text color
        textView.setTextColor(color);
          
        // show snack bar
        snackbar.show();
    }
  
    @Override
    public void onNetworkChange(boolean isConnected) {
        // display snack bar
        showSnackBar(isConnected);
    }
  
    @Override
    protected void onResume() {
        super.onResume();
        // call method
        checkConnection();
    }
  
    @Override
    protected void onPause() {
        super.onPause();
        // call method
        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:

RELATED ARTICLES

Most Popular

Recent Comments