In this blog about Thread in Android Example, you’ll learn about how to set up a thread in android other than the main thread to continue a different process.

Need some career advice or prepping for an Android developer interview? Hit me up on Topmate.io, and let's chat!

Thread in Android Example
Thread in Android Example

I do believe you’re on Facebook and have downloaded a video directly from the Facebook app itself which you can view in offline mode later.

Have you noticed how while the video is downloading, you’re still able to look at your news feed or tag your friends on the status and etc. and when the video is downloaded a Toast message appears that video has been downloaded successfully, This is known as multithreading.

Thread in Android Example
Thread in Android Example

Follow us on Instagram for more Comics on Android, Link here.

Multithreading is the ability of a central processing unit (CPU) or a single core in a multi-core processor to execute multiple processes or threads.

To explain how threading works in even more detail and how you can thread your app too and make it multifunctional and smarter, in this tutorial we will build an Android app.

In App, you’ll be clicking on a button to change a TextView that’ll change after 10 seconds and meanwhile another thread will be generated which will allow you to press that button again (however nothing will happen!)

Thread in Android Example with Handler

To start with this tutorial on handler with runnable in android, do the following steps:

1.Open and create a new Android Project with Empty Activity and name it as ‘Thread App’.

2. Add a textView and a Button in Design View of ‘activity_main.xml’ file. Code for this is as follows:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="com.faultinmycode.bouncyballs.threadapp.MainActivity">

    <Button
        android:id="@+id/changeTextButton"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginBottom="156dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:onClick="clickchangeTextButton"
        android:text="Change TextView"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="280dp"
        android:layout_height="47dp"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="I will change!"
        android:textAlignment="center"
        android:textSize="30sp"
        app:layout_constraintBottom_toTopOf="@+id/changeTextButton"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Using the code above we have created a layout in which there is a text view below which is a button, we have increased the size of text and button for a better view and constrained them to parent layout.

We won’t be making any changes in ‘AndroidManifest.xml’ file.

Creating Layout

Now as defined in activity_main.xml file above, we will create clickchangeTextButton() method in MainActivity.java file. This method will be inside MainActivty class after onCreate() method gets completed.

Coding the Thread in Android

In clickchangeTextButton() method, we will declare a long variable, ‘futureTime’ which will be the current system time (in milliseconds) and we will add 10 seconds (or 10,000 milliseconds) to it. Here is the code for this:

long futureTime = System.currentTimeMillis()+10000;

Now using ‘while’ loop, we will make the Android system to wait for few seconds. Here is the code for this:

while(System.currentTimeMillis() < futureTime){
    synchronized (this){
        try{
            wait(futureTime-System.currentTimeMillis());
        }catch (Exception e){}
    }
}

After we will write 2 lines of code to change the textView. Here is the code for this.

text = findViewById(R.id.textView);
text.setText("I just got Changed!");

Now Run your App on your Virtual device and you’ll notice that as you click the button, the app halts and may crash within or after 10 seconds as the name changes.

It happened because there was a background process going on and the app became irresponsive.

Fixing the issue using thread in Android Example

To fix such issues you need to create another thread for such background process and meanwhile, the main thread will handle the user interaction with the app, like button press in this case.

Now to create a thread in Java, the Runnable interface is used. A Runnable interface is implemented by any class whose instances are intended to be executed by a thread.

So to do this in clickchangeTextButton() method we will write the following code:

Runnable run = new Runnable() {
    @Override
    public void run() {
    };

In the run() method insert the ‘while’ loop which will make the system wait. (Wait we have to write 2 lines of code to start this thread.)

Runnable run = new Runnable() {
    @Override
    public void run() {
        long futureTime = System.currentTimeMillis()+10000;

        while(System.currentTimeMillis() < futureTime){
            synchronized (this){
                try{
                    wait(futureTime-System.currentTimeMillis());
                }catch (Exception e){}
            }
        }
    }
};

So to start a new thread, create it and start it.

Thread newThread = new Thread(run);
newThread.start();

Ok, but now what about the main thread? for this, we need a Handler. Handler is part of the Android system’s framework for managing threads.

A Handler object receives messages and runs code to handle the messages. Normally, you create a Handler for a new thread, but you can also create a Handler that’s connected to an existing thread.

For this, Create a Handler thread in android and pass on the code you want the main thread to run. in this case it is:

Handler handle = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        text = findViewById(R.id.textView);
        text.setText("I just got Changed!");
    }
};

Now this Handler has to be called after 10 seconds, so in the run method itself, after wait loop gets over, insert code:

handle.sendEmptyMessage(0);

Here is the MainActivity.java Code:

package com.androiddvlpr.threadapp;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private TextView text;
    Handler handle = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            text = findViewById(R.id.textView);
            text.setText("I just got Changed!");
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void clickchangeTextButton(View view){

        Runnable run = new Runnable() {
            @Override
            public void run() {
                long futureTime = System.currentTimeMillis()+10000;

                while(System.currentTimeMillis() < futureTime){
                    synchronized (this){
                        try{
                            wait(futureTime-System.currentTimeMillis());
                        }catch (Exception e){}
                    }
                }
                handle.sendEmptyMessage(0);
            }
        };

        Thread newThread = new Thread(run);
        newThread.start();
    }
    
}

TaDa! Run the app. and click the button as many times as you want to.

Leave a Reply

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

You May Also Like