2015-12-30 52 views
3

atm我的實際Android應用程序出現問題。在Android中連續運行Handler任務

對於解釋:

起初,我想表現出一個TextView字符由字符文本。這是我爲這個

tvIntro.setText(""); 
     final Handler textHandler = new Handler(); 

     for(int i=0; i<intro.length();i++){ 

      final int finalCount = i; 
      textHandler.postDelayed(new Runnable() { 
       @Override 
       public void run() { 
        tvIntro.setText(tvIntro.getText() + (intro.charAt(finalCount)+"")); 
       } 
      }, 150 * i); 

     } 

實際的代碼顯示整個文本後,我想打一個聲音不斷改變屏幕的顏色爲5秒。對於這一點,我的代碼是:

myBackground.setBackgroundColor(Color.RED);// set initial colour 
     final Thread blink = new Thread(new Runnable() { 
      public void run() { 
       while (getRunning()) { 
        try { 
         Thread.sleep(100); 
         if(start[0] !=1){ 
          mp.start(); 
          start[0] = 1; 

         } 


        } 
        catch (InterruptedException e) { 
         e.printStackTrace(); 
        } 
        updateColor(myBackground); 
        whichColor = !whichColor; 
       } 
      } 
     }); 

private void updateColor(final RelativeLayout myBackground) { 
    runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      if (whichColor) 
       myBackground.setBackgroundColor(Color.RED); 
      else 
       myBackground.setBackgroundColor(Color.GREEN); 
     } 
    }); 
} 

所有功能都工作,但我想也完成了第一個處理程序,執行第二處理程序之前。此外,第二個處理程序應該在x秒後停止。

我對理解處理程序和線程是如何工作有些問題。 如果你的某個人爲我解決問題,那該多好。

+0

如果你想完成一個處理程序,設置爲null,例如:「textHandler = null;」,否則它將一直存在,直到它的活動完成。 –

回答

1

要延遲任務的執行,直到指定的線程(或線程)完成後,立即在跟帖中加入這一行,你要等待:

myThread.join(); 

然後立即與你希望的代碼遵循它完成後運行。

對於第二個問題,可以設置一個變量爲結束該線程之前要等待的時間量的值(以毫秒爲單位),然後將該值減小100(或選擇任何數量的值告訴它睡覺)每次代碼運行。檢查該值是否小於或等於零,然後如果該條件返回true,則用中斷結束該線程。所以基本上:

long timeToRun = 5000, sleepTime = 100; 

// Your code here... 

Thread.sleep(sleepTime); 
timeToRun -= sleepTime; 
if(timeToRun <= 0) { 
myThread.interrupt(); 
} 

有可能更優雅的方式來做到這一點,但最起碼​​這應該解決您的問題。