Check Internet Android Image Source unsplash.com.

Here is the GitHub link for this project check-internet-android.

Introduction

In most android apps, it is now mandatory to have Internet connectivity either to serve information from the server or sending information to the server. But it is very much important to check whether a network connection is available or not before retrieving from the server.

We will use ConnectivityManager service to determine whether the device is able to check internet connection or not in android. Eventually, we can determine the type of internet connection i.e. mobile data or Wi-Fi. We will implement observable files to check internet connection states so that the app can detect if the status changes in the middle of the operations, therefore, take proper actions. Finally, let users know about connection status change, revert/resume ongoing pending operations, etc.

What is my motivation for doing the project “How to Check Internet Connection on Android Programmatically and from a Button Click using Kotlin”? I developed an android app that uses the internet connection required for users to use it. This blog post will provide precise instructions for its implementation.

Photo Preview

Glossary

CoordinatorLayout is a layout intended for two use cases as shown below:

  1. Container for interaction with specifically one or more child views
  2. Top-level application chrome layout or decor.

CoordinatorLayout provides separate interactions within the same parent. The views can interact with each other. When used as a child of a CoordinatorLayout using the CoordinatorLayout.DefaultBehavior, View classes can specify default behavior.

ConstraintLayout will allow you to create complex layouts with a flat view hierarchy. Just like RelativeLayout, views are laid out according to the relationship between parent layout and the sibling views. Finally, Constraint Layout is more pliable than RelativeLayout and more effective with Android Studio’s Layout Editor.

Steps:

Step 1: Permissions required 

Check internet connection status, will require our app to use the ACCESS_NETWORK_STATE and INTERNET permissions. Therefore, we need to add the above permissions in the AndroidManifest.xml file as shown below.

<?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.denno.internetcheck">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<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"
android:usesCleartextTraffic="true"
tools:ignore="AllowBackup,GoogleAppIndexingWarning"
tools:targetApi="m">
<activity
android:name="com.denno.internetcheck.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>
</application>
view raw AndroidManifest.xml hosted with ❤ by GitHub

Step 2: Adding required dependencies

Go to your app-level build.gradle file and add the following dependency:

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.1.0'
api 'io.reactivex.rxjava2:rxjava:2.2.17'
api 'io.reactivex.rxjava2:rxandroid:2.1.1'
implementation 'androidx.annotation:annotation:1.1.0'
compileOnly 'com.jakewharton.nopen:nopen-annotations:1.0.1'
testImplementation 'junit:junit:4.13'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
view raw build.gradle hosted with ❤ by GitHub

In Android Studio, dependencies allow us to include an external library or local jar files or other library modules in our Android project.

Therefore, if you want to use Kotlin programming language in the app, you have to add the dependency shown below:

implementation ‘androidx.core:core-ktx:1.2.0’

If you want to use material design, add the dependency shown below:

implementation ‘com.google.android.material:material:1.1.0’

Whenever you add a dependency to your Gradle file, it will download the added libraries, and add them to the project so that it’s available in the project. It makes it easy to manage external libraries in our project.

Step 3: Creating the activity_main.xml file

Now, come to your activity_main.xml file. Change your default Constraint Layout to Coordinator Layout. CoordinatorLayout has the ability to coordinate the transition of views inside it. XML solely can be used to describe a layout wherever a Floating Button moves out of the way for incoming Snackbar or Toast. For instance, you can have any view that’s apparently connected to a different Widget and moves on-screen with the Widget. We will take a Floating Action Button in our Coordinator Layout with wrap_content  width and wrap_content height. After adding some additional attributes our Floating Action Button widget will be like this.

<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"
app:srcCompat="@android:drawable/ic_popup_sync" />
view raw FloatingActionButton hosted with ❤ by GitHub

And after that our final activity_main file will look like this.

<?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"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<include layout="@layout/content_main" />
<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"
app:srcCompat="@android:drawable/ic_popup_sync" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
view raw activity_main.xml hosted with ❤ by GitHub

Step 4: Creating the MainActivity.kt file

Now, come to your MainActivity.kt file. So, We will take three variable here like this :

var context = this
var connectivity : ConnectivityManager? = null
var info : NetworkInfo? = null
view raw gistfile1.txt hosted with ❤ by GitHub

After that, we will register an onClickListener on our floating action button. fab is the id of our button in XML. We will make use of a System Service here.

connectivity = context.getSystemService(Service.CONNECTIVITY_SERVICE)
as ConnectivityManager
view raw service hosted with ❤ by GitHub

We will use an if-else condition here. With the help of the activeNetworkInfo method, we will check for the current state of the NetworkInfo. If the NetworkInfo is in the connected state we will display a toast message “Internet Connected“. whereas if the NetworkInfo is not in the connected state then we will display a toast message Internet Disconnected“.

if ( connectivity != null)
{
info = connectivity!!.activeNetworkInfo
if (info != null)
{
if (info!!.state == NetworkInfo.State.CONNECTED)
{
Snackbar.make(view, "Internet Connected", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
}
else
{
Snackbar.make(view, "Internet Disconnected", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
}
view raw toast hosted with ❤ by GitHub

Finally, our complete and final MainActivity.kt will be like this.

package com.denno.internetcheck
import android.app.Service
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Bundle
import android.util.Log
import com.google.android.material.snackbar.Snackbar
import androidx.appcompat.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
class MainActivity : AppCompatActivity() {
private var connectivityDisposable: Disposable? = null
private var internetDisposable: Disposable? = null
var context = this
var connectivity : ConnectivityManager? = null
var info : NetworkInfo? = null
companion object {
private val TAG = "ConnectivityCheck"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
fab.setOnClickListener { view ->
connectivity = context.getSystemService(Service.CONNECTIVITY_SERVICE)
as ConnectivityManager
if ( connectivity != null)
{
info = connectivity!!.activeNetworkInfo
if (info != null)
{
if (info!!.state == NetworkInfo.State.CONNECTED)
{
Snackbar.make(view, "Internet Connected", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
}
else
{
Snackbar.make(view, "Internet Disconnected", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onResume() {
super.onResume()
connectivityDisposable = ConnectivityCheck.observeNetworkConnectivity(applicationContext)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { connectivity ->
Log.d(TAG, connectivity.toString())
val state = connectivity.state()
val name = connectivity.typeName()
connectivity_status.text = String.format("state: %s, typeName: %s", state, name)
}
internetDisposable = ConnectivityCheck.observeInternetConnectivity()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { isConnectedToInternet ->
internet_status.text = isConnectedToInternet.toString()
}
}
override fun onPause() {
super.onPause()
safelyDispose(connectivityDisposable)
safelyDispose(internetDisposable)
}
private fun safelyDispose(disposable: Disposable?) {
if (disposable != null && !disposable.isDisposed) {
disposable.dispose()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
}
view raw MainActivity.kt hosted with ❤ by GitHub

You can use any message in your toast that you want to display. I have used a simple button to check internet status of the app on the click of the button in android. You can use any other widget or icon according to your need. And you can use this code anywhere in your app according to your need. Do not forget to add the permission for accessing the Network_State in your Manifest file because it’s must permission.

Future Directions

After that, display multiple buttons in different Activities and enable implementation of the buttons’ functions only if the device is connected to the internet.

Learning Strategies and Tools

In conclusion, we have learned about how your app has a strict dependency on internet connectivity, it is a good way to detect if the internet connection is available or not when the app starts.  Activities now have to implement the onResume() function to check internet connection in the android device.

Checking the specific API documentation to determine whether the connection is in use. Therefore, LocationRequest objects are for requesting quality of service for location updates. In conclusion,  it has very strong services.

Reflective Analysis

One of the most common uses in android mobile applications is to perform tasks through the check internet. There is no guarantee that the user has always an active internet connection when they operate on our application. So it is safe to know in advance whether the user has an active internet connection or not. Based on this we can action dialog to turn on internet settings, or control internet services being used by the android 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 check internet android using the instructions above. In conclusion, I spent 48 hours finishing the project and the blog. 

Finally, everything is available in this GitHub repository.

Link to the previous post: https://blog.learningdollars.com/2020/08/09/how-to-pick-the-current-location-in-google-maps-android-and-send-it-via-sms/

That’s all for this tutorial!