Internet connection status through Broadcast Receiver in Android

Internet-Connection-Monitoring

Broadcast receiver is a medium through which communication is done with the registered app and the outside OS system.We needs to register and unregister this functionality according to our requirement. At first we have to register each broadcast receiver to get appropriate notification during desired situations. Broadcast receiver receives notification for a small span of time so we can’t do any kind of long running process over here and we need to unregister the same when app goes to background specifically when app is going to pause mode. It notifies the entire application event that is registered within it.For example, the Android system sends broadcasts when various system events occur, such as when the system boots up or the device starts charging, or battery status or internet connectivity changes, or device received some messages or push notifications. We receive all the notification through receiver.

One important thing is that previously we declare receiver to manifest folder but after API level 25 we need to implement context-registered receiversthat we have discussed later.As we need to retrieve data from server and show it to app it is very important that your app is connected to Internet through mobile data or Wi-Fi and connection condition is good enough to fetch the data from server to App so that user can perform their desired functions. For this we need to check internet connection at every point of time when user request for server data.

It is very easy method to check all the time internet connectivity through Broadcast receiver. It will notify at any point of time when network connection is discontinued or network status changed.In this blog Android Application Development Services providerwill discuss about internet connectivity detection through BroadcastReceiver.

Purpose:Information about Internet connection status through Broadcast Receiver in Android.

Scope

IDE: Android Studio.

Procedure:

Step 1:

At first in your android.Manifest file enable internet, access network state permission and register connectivity changeactionfor Broadcast Receiver. Following are codes:

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.manali.myapplication" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET" /> <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/AppTheme" > <activity android:name=".MainActivity" android:label="@string/app_name" android:theme="@style/AppTheme.NoActionBar" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <receiver android:name=".ConnectivityDetection" android:label="ConnectivityDetection"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver> </application> </manifest>

Above we have defined connectivity change intent. So it will notify easily when network connection is changed (Wi-Fi or mobile data) and after that broadcast receiver will be called for notification.

Step 2:

Next we need to create a class ConnectivityDetection which will extend BroadcastReceiver. This is a receiver class which will be notified whenever there is change in network or internet connection.We need to check onReceive() method. This method will be called every time as network changes. Here we have created a Toast message and displaying current network state. You can compose your custom code in here to handle changes in connection state.

importandroid.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class ConnectivityDetectionextends BroadcastReceiver{ @Override public void onReceive(final Context context, final Intent intent) { String status = Networkstatus.getConnectivityStatusString(context); Toast.makeText(context, status, Toast.LENGTH_LONG).show(); } }

Remember that for Wi-Fi result run it on real device. Otherwise it may not detect properly in emulator.

Each time you implement a BroadcastReceiver, you need to register it in the onResume method of your app and unregister it in the onPause method, as follows:

@Override protected void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION); this.registerReceiver(ConnectivityDetection, filter); } @Override public void onPause() { this.unregisterReceiver(ConnectivityDetection); super.onPause(); }

Now we need to implement Networkstatus class. Below we have detected Wi-Fi, Mobile and not connected status. We have assigned a numeric number for every status change. Following are codes:

public class Networkstatus { public static intTYPE_WIFI = 1; public static intTYPE_MOBILE = 2; public static intTYPE_NOT_CONNECTED = 0; public static intgetConnectivityStatus(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfoactiveNetwork = cm.getActiveNetworkInfo(); if (null != activeNetwork) { if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) return TYPE_WIFI; if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) return TYPE_MOBILE; } return TYPE_NOT_CONNECTED; } public static String getConnectivityStatusString(Context context) { intconn = NetworkUtil.getConnectivityStatus(context); String status = null; if (conn == NetworkUtil.TYPE_WIFI) { status = "Wifiis detected"; } else if (conn == NetworkUtil.TYPE_MOBILE) { status = "Mobile data connection is detected"; } else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) { status = "Not connected to Internetconnection"; } return status; } }