2

I am trying to develop an app in Android which has a few actions that need to be executed after a set period of time.

Anything which I can do to fulfil this?

Dr Mido
  • 2,414
  • 4
  • 32
  • 72
Utkarsh
  • 31
  • 1
  • 3

3 Answers3

4

All the answer are correct but initiating handler like below is deprecated.

new Handler()

You need to provide a looper to the handler object. So use below snippet:

Handler(Looper.getMainLooper()).postDelayed({
   // do something
}, 1000)

Looper.getMainLooper() will ensure that code written in that block runs on UI thread.

More details in my other answer: How to handle deprecated Handler in android

Alpha 1
  • 4,118
  • 2
  • 17
  • 23
3

If you're using java to code in android Studio then I suggest you to use the Handler, that will execute your action after a determined span of time

In your activity's onCreate method do this:

 int any_delay_in_ms = 1000; //1Second interval
    new Handler().postDelayed(() -> {
        //TODO Perform your action here
    }, any_delay_in_ms);
Dharman
  • 30,962
  • 25
  • 85
  • 135
Spandan Saxena
  • 232
  • 1
  • 10
1

If you don't use libraries, then handler will be enough

Handler().postDelayed({
   // do smth after delay
}, 1000)
Vlad
  • 7,997
  • 3
  • 56
  • 43