定期间隔后调用特定方法

时间:2011-01-06 06:57:53

标签: android android-2.2-froyo

在我的Android应用程序中,我想在常规时间间隔调用特定方法,即。 “每5秒钟后”......我怎么能这样做??

2 个答案:

答案 0 :(得分:15)

您可以使用Timer进行方法的固定期间执行。

以下是代码示例:

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

答案 1 :(得分:11)

以上链接经过测试,运行正常。这是每秒调用一些方法的代码。你可以随时改变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

    }
};
}