Call Particular Method after regular interval of time

房东的猫 提交于 2019-12-18 13:12:55

问题


In my android application I want to call particular method at regular interval of time ie. "after every 5 seconds"...how can i do that....?


回答1:


You can use Timer for the fixed-period execution of a method.

Here is a sample of code:

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



回答2:


This link above is tested and works fine. This is the code to call some method every second. You can change 1000 (= 1 second) to any time you want (e.g. 3 seconds = 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

    }
};
}


来源:https://stackoverflow.com/questions/4612579/call-particular-method-after-regular-interval-of-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!