在我的android應用程序中,我想要在特定時間間隔即時調用特定的方法。 「每5秒鐘後」......我該怎麼做......?在規律的時間間隔後調用特定方法
6
A
回答
13
您可以使用Timer進行方法的固定期間執行。
下面是代碼的示例:
final long period = 0;
new Timer().schedule(new TimerTask() {
@Override
public void run() {
// do your task here
}
}, 0, period);
10
以上此鏈接被測試和工作正常。這是每秒鐘調用某種方法的代碼。您可以隨時更改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
}
};
}
+0
謝謝。適用於我。 – zwarrior 2016-12-22 06:36:37
嘿兄弟......謝謝.... – Nirav 2011-01-06 07:11:38