2011-09-27 55 views
1

我想在抽兩張抽籤之間暫停一下。我已經嘗試Thread.sleep,處理程序,asyncTask,並得到了相同的結果 - 當活動啓動時,我必須等待一段時間,我設置了第一次繪製,只有當我再次調用同樣的方法(測試)時,我看到第二次繪製,而不是再次看到第一名。有我的代碼:在兩次抽籤之間暫停

public void test(){ 
button.setClickable(false); 
button.setBackgroundColor(Color.DKGRAY); 
view.setFromAtoB(true); 
view.invalidate(); 
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() { 
    @Override 
    protected Void doInBackground(Void... params) { 
     try { 
      Thread.sleep(2000); 
     } catch (InterruptedException e) { 
      } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(Void result) { 
     view.setMoveAB(true); 
     view.postInvalidate(); 
     button.setBackgroundColor(Color.GRAY); 
     button.setClickable(true);   
    } 
}; 
task.execute((Void[])null); 

問題在哪裏?爲什麼我不能看到某種和諧,第一次畫,暫停,第二次畫? :)也許我已經阻止了UI線程。對於繪圖我使用畫布。在onDraw方法我做了一些計算,調用drawRodsAndDiscs方法:

private void drawRodsAndDiscs(Canvas canvas){ 
    Paint paint = new Paint(); 
    drawRods(canvas); 
    paint.setColor(Color.GREEN); 
    paint.setStyle(Paint.Style.STROKE); 
    for (Rect disc : discs) { 
     canvas.drawRect(disc, paint); 
    } 
} 

回答

0

我會使用此代碼爲您的問題。 定時器完成後,它會自動重新啓動。 試試這個:

private boolean running = false; 
private Handler handler; 

public void onCreate(Bundle savedInstanceState) { 
    handler = new Handler(this.getMainLooper()); //Run it in MainLooper 
    this.handler.postDelayed(this.counterThread, 200); //Start timer in 200ms 
} 

private Thread counterThread = new Thread() { 
public void run() { 
     if (isRunning()) { 
      return; 
     } 
     setRunning(true); 

// 10minute until finish, 200ms between ticks 
     CountDownTimer ct = new CountDownTimer(10 * 60 * 1000, 200) { 

      public void onFinish() { 
       setRunning(false); 
      } 

      public void onTick(long time) { 
        //Do your shitznaz 
      } 
     }; 
     ct.start(); 
    } 
}; 

protected boolean isRunning() { 
    return this.running; 
} 
protected void setRunning(boolean b) { 
    this.running = b; 
    if (!b) { 
     // Reset timer 
     this.handler.postDelayed(this.counterThread, 200); //Restarts the timer in 200ms 
    } 
} 
1

嘗試使用簡單CountDownTimer代替了Thread.sleep(INT毫秒);

參考this

0

對於一個簡單的一次性的延遲,你可以使用一個Handler代替:

 Handler handler = new Handler(); 
     handler.postDelayed(new Runnable() {     
      @Override 
      public void run() { 
       view.setMoveAB(true); 
       view.invalidate(); 
       button.setBackgroundColor(Color.GRAY); 
       button.setClickable(true); 
      } 
     }, 2000);