首页 > 代码库 > Android中支持暂停和恢复的Timer和TimerTask封装

Android中支持暂停和恢复的Timer和TimerTask封装

由于Timer和TimerTask类的对象只能用一次,所以如果想多次调度同一样的任务,必须重新实例化。

所以,封装了一个TimerHelper类,测试可用。

 1 public abstract class TimerHelper { 2  3     private Timer mTimer = null; 4  5     public void start(long delay, long period) 6     { 7         stop(); 8  9         mTimer = new Timer();10         mTimer.schedule(new TimerTask() {11             @Override12             public void run() {13 14                 TimerHelper.this.run();15             }16         }, delay, period);17     }18 19     public void stop()20     {21         if (mTimer != null) {22 23             mTimer.cancel();24             mTimer = null;25         }26     }27 28     public TimerHelper() {29 30         mTimer = null;31     }32 33     public abstract void run();34 }

 

 

示例代码:

 1 public class MainActivity extends Activity { 2  3     private final String TAG = this.getClass().getSimpleName(); 4  5     private TimerHelper mTimerHelper = null; 6  7     @Override 8     protected void onCreate(Bundle savedInstanceState) { 9         super.onCreate(savedInstanceState);10         setContentView(R.layout.activity_main);11 12         ///13         mTimerHelper = new TimerHelper() {14             @Override15             public void run() {16 17                 Log.d(TAG, "timer run-----");18             }19         };20     }21 22     @Override23     protected void onResume() {24 25         mTimerHelper.start(500, 5000);26 27         super.onResume();28     }29 30     @Override31     protected void onPause() {32 33         mTimerHelper.stop();34 35         super.onPause();36     }37 }

 

Android中支持暂停和恢复的Timer和TimerTask封装