AndroidAndroid UtilityKotlin

Android Kotlin Listen To Internet Connection Using BroadcastReceiver

One of the most common use in mobile application is to perform tasks through internet. There is no guarantee that user has always active internet connection when they operate on our application. So it is safe to know in advance that user has a active internet connection or not. Based on this we can show messages, action dialog to turn on internet settings or control internet services being used by the app.

Since it is a common task to do in each activity in the application we have created a base class where we implement the internet checking using a broadcast listener.

It is simple two line of code to check internet connectivity. This is achieved by ConnectivityReceiver class. Please see the following code snippet.

Prerequisites

Add following dependency to your module build.gradle file. It is required for Snackbar to work.

dependencies {
  ...
  ...
  implementation 'com.android.support:design:26.1.0'
}

STEP 1. Create BroadcastReceiver Class

Broadcaster Receiver will keep listening to the network changes and it will get callbacks to onReceive() when any changes to network connection is happend. In this event we will notify the base class with network status by calling isConnectedOrConnecting().

package com.devdeeds.samples

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager


/** Author : https://devdeeds.com
 *  Project : Sample Project - Internet status checking
 *  Date : 24 Feb 2018*/

class ConnectivityReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, arg1: Intent) {

        if (connectivityReceiverListener != null) {
            connectivityReceiverListener!!.onNetworkConnectionChanged(isConnectedOrConnecting(context))
        }
    }

    private fun isConnectedOrConnecting(context: Context): Boolean {
        val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = connMgr.activeNetworkInfo
        return networkInfo != null && networkInfo.isConnectedOrConnecting
    }

    interface ConnectivityReceiverListener {
        fun onNetworkConnectionChanged(isConnected: Boolean)
    }

    companion object {
        var connectivityReceiverListener: ConnectivityReceiverListener? = null
    }
}

STEP 2. Create Base Class For The Application

The following class will be the base class for all the other activities in this application. So it is good to have a base class for an application because we can write lot of common tasks in this class and all the other activities implementing from this activity class will get the defined functionalities automatically.

package com.devdeeds.samples

import android.annotation.SuppressLint
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity


/** Author : https://devdeeds.com
 *  Project : Sample Project - Internet status checking
 *  Date : 24 Feb 2018*/


//THIS IS THE BASE ACTIVITY OF ALL ACTIVITIES OF THE APPLICATION.

@SuppressLint("Registered")
open class BaseActivity : AppCompatActivity(), ConnectivityReceiver.ConnectivityReceiverListener {
    private var mSnackBar: Snackbar? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        registerReceiver(ConnectivityReceiver(),
                IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION))
    }


    private fun showMessage(isConnected: Boolean) {



        if (!isConnected) {

            val messageToUser = "You are offline now." //TODO

            mSnackBar = Snackbar.make(findViewById(R.id.rootLayout), messageToUser, Snackbar.LENGTH_LONG) //Assume "rootLayout" as the root layout of every activity.
            mSnackBar?.duration = Snackbar.LENGTH_INDEFINITE
            mSnackBar?.show()
        } else {
            mSnackBar?.dismiss()
        }


    }

    override fun onResume() {
        super.onResume()

        ConnectivityReceiver.connectivityReceiverListener = this
    }

    /**
     * Callback will be called when there is change
     */
    override fun onNetworkConnectionChanged(isConnected: Boolean) {
        showMessage(isConnected)
    }
}

STEP 3. Add Internet Permissions To AndroidManifest.xml

Using ACCESS_NETWORK_STATE permission is required to check the internet connectivity status. INTERNET is required to make internet requests.

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

    <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=".HomeActivity">

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

        </activity>

        <!-- The below code is for android OS version below N -->
        <receiver
            android:name=".ConnectivityReceiver"
            android:enabled="true">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>

    </application>

</manifest>

Finally In your Main Activity Class

Everything is ready you can create your activity class now by extending from the above Base class. Now your main activity class called HomeActivity looks clean. And internet checking has become a part of your activity classes.

package com.devdeeds.samples

import android.os.Bundle

/** Author : https://devdeeds.com
*  Project : Sample Project - Internet status checking
*  Date : 24 Feb 2018*/

class HomeActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home)
    }
}

Result

devdeeds com internet connection checking

About author

Geethu is a teacher by profession, but she likes to research new things and is also interested in writing. Devdeeds is her blog, where she writes all the blog posts related to technology, gadgets, mobile apps, games, and related content.

Leave a Reply

Your email address will not be published. Required fields are marked *