Check Internet Connection in Android

There are many applications created on Android using Android Studio but normally most applications fetch data from the network. That time we will check the internet connection

Also, show the message “No Internet Connection” on the mobile application and it is connected to data and displays a message as “back online “ or internet connected.


Let's create one example of checking an internet connection and disconnecting an internet connection.

We will create a button, and whenever the user presses the button displayed message of check the internet connection of Mobile application 


Step by step implementation

Step 1: Create a new project in Android  or you can use an already created project.  


Step 2: Create an activity_main.xml file in your layout folder . path (res>layout)

 implement the same invoke the following code inside activity_main.xml file. 

 <?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:id="@+id/idRLContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="84dp"
android:src="@drawable/company_logo"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<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"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
Step 3: Create an MainActivity.java file in your package folder .

 Implement the same invoke the following code inside MainActivity.java file.

 import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements ConnectionReceiver.ReceiverListener {

private Button btn_check;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_two);
btn_check = findViewById(R.id.btn_check);
checkConnection();
btn_check.setOnClickListener(view -> {
checkConnection();
});

}

private void checkConnection() {
//create object of Intent filter
IntentFilter intentFilter = new IntentFilter();
//set action on network
intentFilter.addAction("android.new.conn.CONNECTIVITY_CHANGE");
// register receiver
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
registerReceiver(new ConnectionReceiver(), intentFilter, Context.RECEIVER_NOT_EXPORTED);
}
// 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();
//set Toast
showToast(isConnected);
}

private void showToast(boolean isConnected) {
String message;
if (isConnected) {
message = "Connected to Internet";
} else {
message = "Not Connected to Internet";
}
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}

@Override
public void onNetworkChange(boolean isConnected) {
// display Toast
showToast(isConnected);
}

}

 

Step 4: Output of above example

 

Happy coding!

365Bloggy June 5, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive