home top ad

How to check internet Connection in androd studio

Hello friends today we will learn about how to check internet connection in Android studio.
In this article we will see how we will check internet connection in our project.Many times we have to check internet connection in our project and perform any operation in it.We will create this method step by step in our project very easily.In the first method we will check the internet connection through toast and in the second method we will use the layout.

Method First

First of all we will create a new project or in the project in which we want to use it. will implement it Like we will create this project then we will see two files activity_main and MainActivity.java.We will not need any layout in the first method
activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
No one will use this layout in this method.

MainActivity.java
package com.example.internetchecker;

import androidx.appcompat.app.AppCompatActivity;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        checkInternetConnection();
    }

    private void checkInternetConnection() {
        ConnectivityManager manager= (ConnectivityManager) getApplicationContext().getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork=manager.getActiveNetworkInfo();
        if (activeNetwork!=null)
        {
            if (activeNetwork.getType()==ConnectivityManager.TYPE_WIFI)
            {
                Toast.makeText(this, "WiFi enable", Toast.LENGTH_SHORT).show();
            }
            else if (activeNetwork.getType()==ConnectivityManager.TYPE_MOBILE)
            {
                Toast.makeText(this, "Data Network enable", Toast.LENGTH_SHORT).show();
            }

        }
        else
        {
            Toast.makeText(this, "No Internet Connection ..", Toast.LENGTH_SHORT).show();
        }
    }
}
We have created a method checkInternetConnection() inside OnCreate in MainActivity class.We will find out the activenetwork using the ConnectivityManager class and the NetworkInfo class inside the checkInternetConnection() method.After that we will check activeNetwork if it is not null then we will check wifi and mobile data using activeNetwork.getType()==ConnectivityManager.TYPE_WIFI which connection is active.After this we will give some permission in Manifest.

Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.internetchecker">
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
    <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/Theme.InternetChecker">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>


Method Second
Now in the second method we will use a layout which will act as an alert dialog.

activity_main
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="InternetChecking Example"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
In this method also we will not need activity_main but we will use it.

MainActivity.java
package com.example.internetexample;

import androidx.appcompat.app.AppCompatActivity;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {
    NetworkFinder networkFinder=new NetworkFinder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onStart() {
        IntentFilter intentFilter=new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkFinder,intentFilter);
        super.onStart();
    }

    @Override
    protected void onStop() {
        unregisterReceiver(networkFinder);
        super.onStop();
    }
}


NetworkFinder
In this class we have used a class of type NetworkFinder which we will create by right clicking.
package com.example.internetexample;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.text.Layout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;

import androidx.appcompat.widget.AppCompatButton;

public class NetworkFinder extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (!CheckConnection.isConnected(context))
        {
            AlertDialog.Builder builder=new AlertDialog.Builder(context);
            View view= LayoutInflater.from(context).inflate(R.layout.internet_dialog,null);
            builder.setView(view);
            AppCompatButton button=view.findViewById(R.id.retry);
            AlertDialog dialog=builder.create();
            dialog.show();
            dialog.setCancelable(false);
            dialog.getWindow().setGravity(Gravity.CENTER);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismiss();
                    onReceive(context, intent);
                }
            });
        }
    }
}
In this class, we have used an xml layout in this alert using AlertDialog, in which a button has been used which will check internet connection on clicking And to check internet connection we will create a CheckConnection class which will have a boolean method isConnected which will tell us whether there is internet connection or not.

internet_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    android:background="#C4BDBD"
    android:gravity="center"
    tools:context=".MainActivity">

    <ImageView
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:src="@drawable/wifi_off"
        android:layout_gravity="center"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="OPPS !"
        android:gravity="center"
        android:textSize="40sp"
        android:textStyle="bold"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="28sp"
        android:text="No Internet Connection"
        android:gravity="center"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Please check your connection"
        android:gravity="center"
        android:textSize="20sp"/>
    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/retry"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="50dp"
        android:textAllCaps="true"
        android:background="@drawable/button_shape"
        android:text="Retry"/>
</LinearLayout>


CheckConnection
package com.example.internetexample;

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

public class CheckConnection {

    public static final boolean isConnected(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getApplicationContext().getSystemService(context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
            if (networkInfo!=null)
            {
                for (int i=0;i<networkInfo.length;i++)
                {
                    if (networkInfo[i].getState()==NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
After doing this we will give some permission in the manifest file.

Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.internetexample">

    <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/Theme.InternetExample">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
Thanks you

Post a Comment

0 Comments