android Handler.postDelayed use in many places

1.1k views Asked by At

I have an app, which shows a video. At some point I want to give information about videos places. For example, historical places names. I am using this code:

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
  @Override
  public void run() {
    //Do something after 100ms
  }
}, 100);

But when I use this postDelayed comment in many times some message not show or overtake. What is the best solution to show some texts in a delay? For example 5 seconds later show A text, 15 sec later show B text, 30 sec later show C text. my codes look like this:

        switch ()

        case 1:
        openVideo(video1)

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
          @Override
          public void run() {
            //my message
          }
        }, 4000);

break;
        case 2:

        openVideo(video2)

        final Handler handler2 = new Handler();
        handler2.postDelayed(new Runnable() {
          @Override
          public void run() {
            //my second message
          }
        }, 3000);


        handler2.postDelayed(new Runnable() {
          @Override
          public void run() {
            //my third message
          }
        }, 15000);

break;
2

There are 2 answers

3
Naitik On

Use Timer for every second...

new Timer().scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                 //put you code here 
                 //or set switch case for time 5,10,15 seconds
                }
            }, 0, 1000);//put here time 1000 milliseconds=1 second
3
Ranjithkumar On

Use multi-runnable.. Increase your duration for each text.

int mDuration=0,mAnimationDuration=5000;


mDuration=mDuration+mAnimationDuration;

//it called after 5 seconds
handler.postDelayed(new Runnable() {
@Override
 public void run() {
   //Your first text
 }
}, mDuration);

mDuration=mDuration+mAnimationDuration;

//it called after 10 seconds
handler.postDelayed(new Runnable() {
@Override
public void run() {
 //Your second text
}
}, mDuration);

mDuration=mDuration+mAnimationDuration;

//it called after 15 seconds
handler.postDelayed(new Runnable() {
@Override
 public void run() {
  //Your third text
}
}, mDuration);