android - update UI by calling AsyncTask objects many times -


i making simple app , display questions , user within 10 seconds should answer or click next, when user click next , next question displayed , timer goes again 10 seconds. using asytask handle time counter , when click next button , next question displayed timer delay 2 seconds or start again 10 , example: on screen : question 1 displayed , time left 8 seconds . when click next button question 2 displayed time 8 after 2 or 3 seconds time goes 10 , start decreasing : question : there better way handle ? , why when next question displayed time hang 2 or 3 seconds start again 10 here code :

    // method called reset timer 10 , display next      question    private void displynextquestion(){   // cancel current thread .       decrease_timer.cancel(true);         decrease_timer =new decrease_timer();    // execute again , set timer 10 seconds    decrease_timer.executeonexecutor(asynctask.thread_pool_executor,10);    // code      }      private class decrease_timer extends asynctask <integer ,integer,void>{  @override protected void doinbackground(integer... integers) {      (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]); } 

} }

use countdowntimer, more easy:

countdowntimer countdowntimer = new countdowntimer(10000, 1000) {      public void ontick(long millisuntilfinished) {         mtextfield.settext("seconds remaining: " + millisuntilfinished / 1000);     }      public void onfinish() {         mtextfield.settext("done!");     } }; 

the first argument in countdowntimer constructor total time in milliseconds, , second argument interval along way receive ontick(long) callbacks.

to restart, call:

countdowntimer.cancel(); countdowntimer.start(); 

see more in https://developer.android.com/reference/android/os/countdowntimer.html


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -