Android 在固定的时间间隔后调用特定的方法

Android 在固定的时间间隔后调用特定的方法,android,android-2.2-froyo,Android,Android 2.2 Froyo,在我的android应用程序中,我希望以固定的时间间隔调用特定的方法,即“每隔5秒”…我如何才能做到这一点?您可以使用固定时间执行方法 下面是一个代码示例: final long period = 0; new Timer().schedule(new TimerTask() { @Override public void run() { // do your task here } }, 0, period); 上面的链接经过测试,工作正常。这是每秒调

在我的android应用程序中,我希望以固定的时间间隔调用特定的方法,即“每隔5秒”…我如何才能做到这一点?

您可以使用固定时间执行方法

下面是一个代码示例:

final long period = 0;
new Timer().schedule(new TimerTask() {
    @Override
    public void run() {
        // do your task here
    }
}, 0, period);

上面的链接经过测试,工作正常。这是每秒调用某个方法的代码。您可以将1000(=1秒)更改为您想要的任何时间(例如,3秒=3000)


谢谢对我有用。
public class myActivity extends Activity {

private Timer myTimer;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);

    myTimer = new Timer();
    myTimer.schedule(new TimerTask() {          
        @Override
        public void run() {
            TimerMethod();
        }

    }, 0, 1000);
}

private void TimerMethod()
{
    //This method is called directly by the timer
    //and runs in the same thread as the timer.

    //We call the method that will work with the UI
    //through the runOnUiThread method.
    this.runOnUiThread(Timer_Tick);
}


private Runnable Timer_Tick = new Runnable() {
    public void run() {

    //This method runs in the same thread as the UI.               

    //Do something to the UI thread here

    }
};
}