Android Handler – Background Thread Communicate with UI thread

Every Android app has own thread that runs UI objects, this thread is called Main Thread or UI Thread. If your app is running a background thread long operation and you want to publish the result in-app screen. But here is a problem, your app task is running in the background and Where UI Thread is different and only object running on the UI Thread have to access to other objects in UI Thread. So your background app task can’t communicate or send data directly to Main Thread (UI Thread). That time you have to use an Android Handler, that’s running on UI Thread.

Android Handler - Background Thread Communicate with UI thread

In this tutorial, you will learn the following:

  1. Overview Android Handler
  2. Complete example Background thread communicate to the Main thread using Handler.

Android Handler allows you to communicate with the UI thread from other background thread. It’s useful in android as android doesn’t allow other threads to communicate directly with UI thread.

Let’s Build an Android Handler example in kotlin:

In Android app development using kotlin language. In the example on Click button thread will run and update the UI counter and progress bar using Handler. You can see the counting in TextView label . Let’s see the steps to how to do it.

Step 1. Create a new project “Build Your First Android App in Kotlin
Step 2. Add following code in “activity_main.xml” layout file

Where Button will start the thread and Textview show count and ProgressBar will show update progress.

Step 3. Open the “MainActivity.kt” and add following code

On clicking button – where we are updating ProgressBar and while updating ProgressBar same time updating TextView by using the same Handler.

Step 4. Now Run the application, in an emulator or On you android device

Output screenshot Android Handler Dialog :

Download source code Android Handler in kotlin

https://github.com/EyeHunts/AndroidHandler

Note : This example (Project) is developed in Android Studio 3.1.3 . Tested on Android 9 ( Android-P), compile SDK version API 27: Android 8.0 (Oreo)

MinSdkVersion=”15″

TargetSdkVersion=”27″

Coding in Kotlin

Any suggestions always welcome, please do comment.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.