以下的程式碼在onResume()後以Log定時輸出
System.currentTimeMillis() 直到onPause()停止。
package com.example.bert.myapplication; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import java.util.Timer; import java.util.TimerTask; public class MainActivity extends ActionBarActivity { //宣告Timer及TimerTask Timer timer; TimerTask timerTask; @Override protected void onResume() { super.onResume(); startTimer(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onPause() { super.onPause(); stoptimertask(); } public void startTimer() { //set a new Timer timer = new Timer(); //initialize the TimerTask's job initializeTimerTask(); //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms timer.schedule(timerTask,5000,10000); } public void initializeTimerTask() { timerTask = new TimerTask() { public void run() { Log.d("test", String.valueOf(System.currentTimeMillis())); } }; } public void stoptimertask() { //stop the timer, if it's not already null if (timer != null) { timer.cancel(); timer = null; } } }
執行結果,可以看到log輸出,每間隔10秒的一次輸出
沒有留言:
張貼留言