【发布时间】:2011-06-04 11:56:01
【问题描述】:
在我的 android 应用程序中,我想定期调用特定的方法,即。 “每 5 秒后”......我该怎么做......?
【问题讨论】:
在我的 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
}
};
}
【讨论】: