Hi Guys, Welcome to Proto Coders Point, In this Android Tutorial we will create a demo on how to check the state of internet connection using android broadcast receiver.
How to Check Internet Connection in android using Broadcast Receiver
Step 1: Create a new Project in android studio
OffCourse you need to Create a new Project,
Go to File > New Project and then fill all the details like app name, android package name, etc and hit the finish button to create new android project.
Step 2: add Network state permission on AndroidManifest.xml
Now, Open AndroidManifest.xml file and ACCESS_NETWORK_STATE permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Step 3: Create a customDialog xml layout
This customDialog will be shown to user when user android device is not connect to internet.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:background="#024BFF" android:gravity="center" android:layout_height="match_parent"> <ImageView android:layout_width="120dp" android:layout_height="120dp" android:src="@drawable/no_internet" android:layout_gravity="center"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Ooops!" android:gravity="center" android:textColor="#FFF" android:textSize="40sp"/> <TextView android:id="@+id/nettext" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="No Internet Connection found" android:textColor="#FFF" android:textSize="15sp" android:layout_marginBottom="10dp" android:gravity="center"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="ON YOUR DATA AND HIT RESTART" android:textColor="#FFF" android:textSize="15sp" android:layout_marginBottom="10dp" android:gravity="center"/> <Button android:id="@+id/restartapp" android:layout_width="300dp" android:layout_height="50dp" android:text="Restart" android:textSize="20sp" android:background="@android:color/holo_green_light"/> </LinearLayout>
Step 4: Create a new java class, NetworkUtil
Then, on the left Project section
app > java > your package name ( right click ) > New > Java Class
Create a NetworkUtil class to find the network status as show below.
NetworkUtil.java
import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; class NetworkUtil { public static String getConnectivityStatusString(Context context) { String status = null; ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null) { if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) { status = "Wifi enabled"; return status; } else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) { status = "Mobile data enabled"; return status; } } else { status = "No internet is available"; return status; } return status; } }
Step 5 : Create a broadcast receiver class
This broadcart receiver in android will keep track of when internet is connected or disconnected by using which we can easily update UI updates to the users.
app > java > your package name ( right click ) > New > Java Class
MyReceiver.java
import android.app.Activity; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class MyReceiver extends BroadcastReceiver { Dialog dialog; TextView nettext; @Override public void onReceive(final Context context, final Intent intent) { String status = NetworkUtil.getConnectivityStatusString(context); dialog = new Dialog(context,android.R.style.Theme_NoTitleBar_Fullscreen); dialog.setContentView(R.layout.customdialog); Button restartapp = (Button)dialog.findViewById(R.id.restartapp); nettext =(TextView)dialog.findViewById(R.id.nettext); restartapp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((Activity) context).finish(); Log.d("clickedbutton","yes"); Intent i = new Intent(context, MainActivity.class); context.startActivity(i); } }); Log.d("network",status); if(status.isEmpty()||status.equals("No internet is available")||status.equals("No Internet Connection")) { status="No Internet Connection"; dialog.show(); } Toast.makeText(context, status, Toast.LENGTH_LONG).show(); } }
Step 6 : update broadcast receiver in androidmanifest.xml
Then you need to update the broadcast receiver, so add the <receiver> tag in manifest file.
Under <application> tag just all the below <receiver> tag code.
<receiver android:name = "MyReceiver"> <intent-filter> <action android:name = "android.net.conn.CONNECTIVITY_CHANGE" tools:ignore="BatteryLife" /> <action android:name = "android.net.wifi.WIFI_STATE_CHANGED" /> </intent-filter> </receiver>
Step 7 : Call Broadcast receive from MainActivity.java
Then you need to make a call to broadcast receiver so that broadcast receiver get activited from your android app.
This broadcast reciever will keep track of CONNECTIVITY_ACTION like internet connectivity on/off.
MainActivity.java
import android.content.BroadcastReceiver; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity{ private BroadcastReceiver MyReceiver = null; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); MyReceiver = new MyReceiver(); broadcastIntent(); } public void broadcastIntent() { registerReceiver(MyReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } @Override protected void onPause() { super.onPause(); unregisterReceiver(MyReceiver); } }
Finally your android app is ready to check internet connection is on or off.