【问题标题】:How to implement delay in android?如何在android中实现延迟?
【发布时间】:2014-08-21 21:58:15
【问题描述】:

我想在按下按钮时每 2 秒打印一次序列号。我使用了以下代码:

int j=0;
button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            c=Calendar.getInstance();
            Delay(2 ,c.get(Calendar.SECOND));
            if(j++<5)
              t.setText("number "+j);

            }

    });

public void Delay(int p,int q){

    int z=0;

    while(z<p){
        c=Calendar.getInstance();
        i= c.get(Calendar.SECOND);
        z=i-q;
    }

    return ;
}

但此代码在 10 秒结束时直接打印“数字 5”。 如何打印“数字 1”、“数字 2”、“数字 3”....每 2 秒依次打印一次。

【问题讨论】:

标签: android delay


【解决方案1】:

请注意,如果您在 UI 线程上执行此操作,您将阻塞 UI 线程 10 秒。最好有一个单独的线程来执行此操作:

button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View arg0) {
        new Thread() {
            public void run() {
                for(int j=1; j<=5; i++) {
                     runOnUiThread(new Runnable() {
                         @Override
                         public void run() { t.setText("number " + j); }
                    });
                    SystemClock.sleep(2000);
                }
            }
        }.start();
    }
});

此代码启动一个新线程(因此不会阻塞 UI),它从 1 到 5 迭代输出数字(在 UI 线程上,因为它正在更改 UI),然后休眠 2 秒。

【讨论】:

    【解决方案2】:

    使用 Runnable 发布到绑定到您应用的 UI 线程的处理程序,而不是休眠或延迟。如果您在 onClick() 方法中休眠或延迟,则您正在阻塞 UI 线程,这将使您的 UI 无响应。

    public class MyActivity extends Activity implements Handler.Callback {
        ...
        private Handler mHandler = new Handler(this);
        private int     mNumber = 0;
        ...
        @Override
        public void onClick(View v) {
            mNumber++;
            mHandler.postDelayed(new Runnable() {
                public void run() {
                    t.setText("number: " + mNumber);
                }, 2000);
        }
    }
    

    【讨论】:

      【解决方案3】:

      您可以为此使用CountDownTimer。您只需要定义时间量和更新频率即可。您只需稍微调整逻辑即可向上打印数字。

      button.setOnClickListener(new OnClickListener() {
      
      @Override
      public void onClick(View arg0) {
          new CountDownTimer(60000, 2000) {
      
             public void onTick(long millisUntilFinished) {
                 mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
             }
      
             public void onFinish() {
               mTextField.setText("done!");
             }
          }.start();
      }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-03
        • 2014-06-02
        • 1970-01-01
        • 1970-01-01
        • 2012-04-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多