【问题标题】:update UI by calling AsyncTask objects many times通过多次调用 AsyncTask 对象来更新 UI
【发布时间】:2017-07-28 08:10:04
【问题描述】:

我正在制作一个简单的应用程序,显示问题,用户应在 10 秒内回答或单击下一步,当用户单击下一步时,将显示下一个问题并且计时器再次进入 10 秒。 我正在使用 Asytask 来处理计时器,但是当我单击下一个按钮时,会显示下一个问题,但计时器延迟像 2 秒左右从 10 重新开始, 例如: 屏幕上:显示第1题,剩余​​时间为8秒。 当我单击下一步按钮时 显示问题 2,但时间为 8,然后在 2 或 3 秒后时间变为 10 并开始减少: 我的问题是: 有没有更好的方法来处理这个?为什么在显示下一个问题时,时间会像 2 或 3 秒一样挂起,然后从 10 秒重新开始 这是我的代码:

    // this method is called to reset the timer to 10 and display next 
    question

  private void displynextquestion(){
  // cancel the current thread .

     decrease_timer.cancel(true);     
   decrease_timer =new Decrease_timer();
   // execute again and set the timer to 10 seconds
   decrease_timer.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,10);
   // some code 
    }
     private class Decrease_timer extends AsyncTask <Integer ,Integer,Void>{

@Override
protected Void doInBackground(Integer... integers) {

    for (int i=integers[0];i>=0;i--){
        publishProgress(i);
        try {
            Thread.sleep(1000);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    return null;
}

@Override
protected void onProgressUpdate(Integer... values) {
    super.onProgressUpdate(values);
    timeview.setText(""+values[0]);
}

} }

【问题讨论】:

    标签: android multithreading android-asynctask


    【解决方案1】:

    使用 CountDownTimer,更简单:

    CountDownTimer countDownTimer = new CountDownTimer(10000, 1000) {
    
        public void onTick(long millisUntilFinished) {
            mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
        }
    
        public void onFinish() {
            mTextField.setText("done!");
        }
    };
    

    CountDownTimer 构造函数中的第一个参数是以毫秒为单位的总时间,第二个参数是接收 onTick(long) 回调的时间间隔。

    要重新启动,只需调用:

    countDownTimer.cancel();
    countDownTimer.start();
    

    https://developer.android.com/reference/android/os/CountDownTimer.html中查看更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多