2012-04-08 34 views
0

我開發一個Android應用程序,我需要定期(每秒幾次)從UI線程Activity類執行一些代碼。 我看到過類似的問題,如Android repetitive task,但我需要的是將我的Activity設置爲偵聽器,並以某種方式偵聽計時器,以便每X毫秒執行一次方法。如何在活動中定期調用方法?

事情是這樣的:

class myActivity extends Activity{ 
    //things 

    //This method must be called every X milliseconds 
    private repetitive_method(){ 
     .... 
    } 

    //more things 
} 

有一些recomended辦法做到這一點?

回答

0

這可能會有幫助。請注意,在檢查其是否爲null並致電runOnUiThread()之間,仍存在競爭情況,其中mActivity可能變爲空。

class UpdaterThread extends Thread { 
    /** Frequency/sleep duration in milliseconds */ 
    public static final int FREQUENCY = 250;   
    private volatile boolean mFinished;  
    private Activity mActivity; 

    public UpdaterThread(Activity activity) { 
     mActivity = activity; 
    } 

    public void run() { 
     while (!mFinished) { 
      try { 
       if (mActivity != null) { 
        // Your method. 
        mActivity.runOnUiThread(repetitive_method()); 
       } 
       Thread.sleep(FREQUENCY); 
      } catch (InterruptedException ignored) {} 
     } 
    } 

    public void quit() { 
     mFinished = true; 
    } 
} 
+0

它肯定會工作,但Timer和Handler類提供了有趣的方法,特別是與UI線程交互,因此是最常見的實現。 – znat 2012-04-08 12:30:46

0

嘗試......

Timer myTimer; 
@Override 
protected void onStart() { 
    super.onStart(); 
    myTimer= new Timer(); 
    //this will update every minute 
    myTimer.scheduleAtFixedRate(new UpdateMyTimerTask(), 0, 
      60000); 

} 

public class UpdateMyTimerTask extends TimerTask { 

    @Override 
    public void run() { 
     //your method 
     printAndroidLabel(); 
    } 

} 

@Override 
protected void onStop() { 
    super.onStop(); 
    //stop timer 
    myTimer.cancel(); 
} 

public void printAndroidLabel(){ 
    System.out.println("Hi Android!"); 
}