在固定的时间间隔内调用特定的方法[英] Call Particular Method after regular interval of time

本文是小编为大家收集整理的关于在固定的时间间隔内调用特定的方法的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

在我的Android应用程序中,我想在规则的时间间隔内呼叫特定方法,即. "每5秒钟之后"......我怎么能这样做......?

推荐答案

您可以使用 timer 用于固定期间执行方法.

这里是代码示例:

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

    }
};
}

本文地址:https://www.itbaoku.cn/post/102454.html

问题描述

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....?

推荐答案

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);

其他推荐答案

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

    }
};
}