android Handler.postDelayed在很多地方使用

时间:2016-12-23 09:00:52

标签: android android-handler

我有一个显示视频的应用。在某些时候,我想提供有关视频地点的信息。例如,历史名称。我正在使用此代码:

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

但是,当我多次使用此postDelayed评论时,某些消息未显示或超过。什么是延迟显示一些文本的最佳解决方案?例如5秒后显示A文本,15秒后显示B文本,30秒后显示C文本。我的代码看起来像这样:

        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 个答案:

答案 0 :(得分:2)

使用multi-runnable ..增加每个文本的持续时间。

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);

答案 1 :(得分:1)

每秒使用一次计时器......

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