0

In Eclipse, I found that using a TimeLine and a KeyFrame I can delay the execution of code, for example, to wait 4 seconds before playing a media I used this code:

Timeline timeline = new Timeline();
KeyFrame keyframe = new KeyFrame(Duration.millis(4000), DelayAnimation ->
{
    GeneralMethods PlayMusic = new GeneralMethods();
    PlayMusic.playMusic(mediaPlayer);
});

timeline.getKeyFrames().add(keyframe);
timeline.play();

The previous code works fine in Eclipse and I did not need to create a new thread.

My question is, Is there a similar way to delay the execution of code in Android?

I found a way to delay the execution of code, but it is using a handler, that is to say, creating a new thread. I would like to delay without using a thread, is it possible?

2 Answers2

2

Handler is what you use to delay something in your thread. In the following case, the handler makes your UI TextView disappear after waiting for ten seconds;

private void makeTextViewDisappear(){
yourTV.setVisibility(View.VISIBLE);
new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                   yourTV.setVisibility(View.INVISIBLE);
         // OR yourTV.setVisibility(View.GONE) to reclaim the space 
                }
            }, 10000);
}

As you can see, there is no new thread.

Enzokie
  • 7,365
  • 6
  • 33
  • 39
Zac
  • 695
  • 1
  • 11
  • 34
  • Thank you. The code I found was using a new Thread, but in your code I can see there is not one, just the runnable managed by the handler. I was just wondering if there is an alternative to the handler, or is the handler the only way to insert a delay? – Daniel Sainz Jan 06 '17 at 15:00
0

Thread.sleep(10000)

It will delay your current thread by 10 secs