Skip to main content

Handler with runnable in Android Example Tutorial | FaultInMyCode

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

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 a status and etc. and when the video is downloaded a Toast message appears that video has been downloaded successfully, This is known as multithreading.

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 which 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!)

Handler with runnable in Android

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:

activity_main.xml
<?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>
 
3. 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.

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

5. 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.

6. 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;
 
7. 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){}
    }
}
 
8. 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!");
 
9. 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.

10. It happened because there was a background process going on and the app became irresponsive. 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.

11. 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() {
    };
 
12. 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){}
            }
        }
    }
};
 
13. So to start a new thread, create it and start it.

Thread newThread = new Thread(run);
newThread.start();
 
14. 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.

15. For this, Create a Handler 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!");
    }
};
 
16. 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);
 
17. Here is the MainActivity.java Code:

MainActivity.java
package com.faultinmycode.bouncyballs.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();
    }
    
}
 
18. TaDa! Run the app. and click the button as many times as you want to.

Download This Android Project from the link, Click here.

Comments

Popular posts from this blog

How To Open PDF File in Android Application Example Included

Want to know How To Open PDF File in Android Application Example. To open a PDF File in Android Application, your app can take help from Free Android library available on Github.

Here are few apps made from PDF Library you can look at, click here to know more.

By using Android Library you are not only leveraging the hard work from another developer but also making it easier and quicker to develop an android app.
How To Open PDF File in Android Application Example  In this tutorial series, we will teach you how to open a pdf file in Android Application Example included with the help of Android PDFViewer library developed by Barteksc.

Get inspirtion from here: Top 7 PDF Download for Mobile Android Apps

Before I proceed further, here is the screenshot of the kind of PDF Viewer that’ll be created using Android Studio.



 How To Open PDF File in Android Application Example

The app will open a specified pdf file which will be copied in the assets folder of your Android studio project. I'v…

Open Weather Map API Example | Create Android Weather App

In this tutorial blog, using open weather map API example, we will create an Android weather app. The Android App will able to access Open weather map website server and access weather details of particular location.

The App will look similar to the image shown below. It will fetch real time weather of the location provided in MainActivity.Java file.


Software / Files used:Android Studio (Version 3.x) Files Edited / Created:activity_main.xmlMainActivity.JavaWeather.JavaAndroidManifest.xml Steps Involved in Open Weather Map API Example: Here are the Steps you need to follow on ‘Open Weather map API Example’ to create Android Weather App:

1. Open the Open Weather map API link provided here. Sign up for Current Weather Data API key here.

2. Once the key is received, save it to notepad or on stick notes.

3. Open Android Studio and create a new Project with name, ‘FIMC Weather App’, we will select an empty activity in the wizard and wait for Gradle build.



4. Open AndroidManifest.xml…

Android Live Wallpaper Tutorial (using Android Studio 3.x) | FaultInMyCode

The Android Live Wallpapers are the way to redesign your mobile background into something amazing animated GIF using different effects and motions. Many novice developers are making good money by Henceforth here is Android Live Wallpaper tutorial for you to build your own Live wallpaper and start earning today as a developer!



This tutorial is a part of our Blog series on ‘Roadway to Android Development Course’, its suitable for Beginners to programming as well as the android enthusiast to learn about Android development and build their own apps.

In this tutorial for beginners, you’ll learn how by using Android Studio 3.0 and by having basic knowledge of Java, we will teach you to build your own Live wallpaper for Android which you may later publish in the Google Play Store. We assume you have some experience with Android studio, if not please check how to build your own calculator app and how to create simple login app in Android Studio 3.x tutorial.
How to build Android …