Detecting internet connection status in your app is very easy and won’t take more than 5mins. In this article you will learn how to detect internet connection status manually and automatically. Using broadcast receiver, your app will be automatically notified when there is a change in network connection.
This provides easy way do any changes in the app like hiding few button (like WhatsApp hides send, upload icon when there is not internet), navigation user to another screen, or just show a Snackbar message.
DEMO
Creating New Project
1. Create a new project in Android Studio from File ⇒ New ⇒ New Project. When it prompts you to select the default activity, select Blank Activity and proceed.
2. Create a class named ConnectivityReceiver.java and extend it from BroadcastReceiver. This is a receiver class which will be notified whenever there is change in network / internet connection.
ConnectivityReceiver.java
package com.codedecode.yashpwr; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; public class ConnectivityReceiver extends BroadcastReceiver { public static ConnectivityReceiverListener connectivityReceiverListener; @Override public void onReceive(Context context, Intent intent) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); if (connectivityReceiverListener != null) { connectivityReceiverListener.onNetworkConnectionChanged(isConnected); } } public static boolean isConnected() { ConnectivityManager cm = (ConnectivityManager) MyApplication.getInstance().getApplicationContext() .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); return (activeNetwork != null && activeNetwork.isConnectedOrConnecting()); } public interface ConnectivityReceiverListener { void onNetworkConnectionChanged(boolean isConnected); } }
3. Create another class named MyApplication.java and extend it from Application. This class will be called whenever app is launched. Here setConnectivityListener() method is used to initiate the connectivity listener.
MyApplication.java
package com.codedecode.yashpwr; import android.app.Application; public class MyApplication extends Application { private static MyApplication mInstance; @Override public void onCreate() { super.onCreate(); mInstance = this; } public static synchronized MyApplication getInstance() { return mInstance; } public void setConnectivityListener(ConnectivityReceiver.ConnectivityReceiverListener listener) { ConnectivityReceiver.connectivityReceiverListener = listener; } }
4. Open AndroidManifest.xml and do the below changes.
- Add MyApplication to <application> tag.
- Add ConnectivityReceiver as <receiver>.
- Declare INTERNET and ACCESS_NETWORK_STATE permissions.
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" package="com.codedecode.yashpwr"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:name=".MyApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" tools:ignore="AllowBackup"> <receiver android:name=".ConnectivityReceiver"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> <action android:name="android.net.wifi.WIFI_STATE_CHANGED" /> </intent-filter> </receiver> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".SecondActivity" android:label="@string/title_activity_second" android:parentActivityName=".MainActivity"> <meta-data android:name="android.support.PARENT_ACTIVITY" android:value=".MainActivity" /> </activity> </application> </manifest>
Broadcasting Internet Status to All Activities
Now we have all the setup ready. Let’s see how to notify an activity when the device is connected or disconnected from internet.
5. Open layout file main activity activity_main.xml add the below layout.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <androidx.coordinatorlayout.widget.CoordinatorLayout 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" android:fitsSystemWindows="true" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="@dimen/activity_vertical_margin" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:textStyle="bold" android:text="Turn on/off wifi or Mobile Network to notify the app about connection status." /> <Button android:id="@+id/btn_check" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:text="Check Connection" /> </LinearLayout> <com.google.android.material.floatingactionbutton.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin" android:src="@drawable/ic_add_white_24dp" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>
6. Open your MainActivity.java and do the below changes to receive the internet status.
- Register the connection change listener in onResume() method by calling MyApplication.getInstance().setConnectivityListener(this).
- Implement the activity from ConnectivityReceiver.ConnectivityReceiverListener which will override onNetworkConnectionChanged() method.
- onNetworkConnectionChanged() method will be triggered whenever device is connected / disconnected from internet. You need to take appropriate action here.
Follow the above same three steps in all other activities in which in you want to notify the internet status.
MainActivity.java
package com.codedecode.yashpwr; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; 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.floatingactionbutton.FloatingActionButton; import com.google.android.material.snackbar.Snackbar; public class MainActivity extends AppCompatActivity implements ConnectivityReceiver.ConnectivityReceiverListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btnCheck = findViewById(R.id.btn_check); FloatingActionButton fab = findViewById(R.id.fab); IntentFilter filter = new IntentFilter(); filter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); registerReceiver(new ConnectivityReceiver(), filter); // Manually checking internet connection checkConnection(); btnCheck.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Manually checking internet connection checkConnection(); } }); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, SecondActivity.class)); } }); } private void checkConnection() { boolean isConnected = ConnectivityReceiver.isConnected(); showSnack(isConnected); } private void showSnack(boolean isConnected) { String message; int color; if (isConnected) { message = "Good! Connected to Internet"; color = Color.WHITE; } else { message = "Sorry! Not connected to internet"; color = Color.RED; } Snackbar snackbar = Snackbar.make(findViewById(R.id.fab), message, Snackbar.LENGTH_LONG); View sbView = snackbar.getView(); TextView textView = sbView.findViewById(R.id.snackbar_text); textView.setTextColor(color); snackbar.show(); } /** * Callback will be triggered when there is change in * network connection */ @Override public void onNetworkConnectionChanged(boolean isConnected) { showSnack(isConnected); } @Override protected void onResume() { super.onResume(); checkConnection(); // register connection status listener MyApplication.getInstance().setConnectivityListener(this); } @Override protected void onPause() { super.onPause(); checkConnection(); // register connection status listener MyApplication.getInstance().setConnectivityListener(this); } }
Run the project and try turning off / on wifi or mobile data. You can notice a Snackbar is shown with network connection status.
Happy Coding 🙂
Yash Pawar
Yash is hardcore programmer and programming has been his passion since he compiled his first hello-world program. Solving real problems of developers through tutorials has always been interesting part for him.