1. Using Handler
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val myButton: Button = findViewById(R.id.my_button)
myButton.setOnClickListener {
// Wait for 10 seconds (10,000 milliseconds)
Handler(Looper.getMainLooper()).postDelayed({
// Action to perform after 10 seconds
Toast.makeText(this, "Action performed after 10 seconds!", Toast.LENGTH_SHORT).show()
}, 10000) // 10 seconds delay
}
}
}
2. Using Kotlin Coroutines
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val myButton: Button = findViewById(R.id.my_button)
myButton.setOnClickListener {
CoroutineScope(Dispatchers.Main).launch {
delay(10000) // 10 seconds delay
// Action to perform after 10 seconds
Toast.makeText(this@MainActivity, "Action performed after 10 seconds!", Toast.LENGTH_SHORT).show()
}
}
}
}
Explanation:
Handler (1st method): It uses Handler with a delay to post a task to the main thread after a specified delay.
Coroutines (2nd method): This uses Kotlin coroutines for asynchronous programming. It pauses the execution for 10 seconds using delay() and then performs the action.
Both approaches will trigger the action 10 seconds after the button is clicked.