How to delay (wait for) the execution of methods by certain duration/ time in your Android App?

In this short video it shows how one can delay the execution of certain methods in your Android App. It creates a new runnable and calls the runnable after the specified delay using the handler object. Executing the method in another runnable ensure that the main thread is not impacted in the execution flow.

I hope you like this video. For any questions, suggestions or appreciation please contact us at: https://programmerworld.co/contact/ or email at: programmerworld1990@gmail.com

Complete source code and other details:

package com.programmerworld.delayapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
private TextView textView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textView = findViewById(R.id.textView);
}

public void buttonDelay(View view){
long longTime1 = System.currentTimeMillis();
Runnable runnable = new Runnable() { //New Thread
@Override
public void run() {
long longTime2 = System.currentTimeMillis();
long longTimeDifference = longTime2 - longTime1;
textView.setText(String.valueOf(longTimeDifference));
}
};
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(runnable, 3000); // delayed by 3 seconds
}
}

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="34sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="203dp"
android:layout_height="96dp"
android:layout_marginStart="112dp"
android:layout_marginTop="92dp"
android:onClick="buttonDelay"
android:text="Delay"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

No Changes in manifest, gradle or any other files required.

Leave a Reply