这篇主要是接上篇“多线程”,因为定时器只能用于多线程中。
Android实现定时器有这些方式:
1. 标准的Java类Timer+TimerTask+Handler; 而Android推荐使用ScheduledThreadPoolExecutor替代TimerTask,
API上写到:
When this thread is busy running a task, runnable tasks may be subject to delays.
This class does not offer guarantees about the real-time nature of task scheduling.
2. 简单化的Handler+Runnable,通过Handler.postDelayed实现;这个和Timer应该是相同的问题。
3. Thread+Handler方式,通过Thread.sleep来实现。
不推荐使用,因为这种方式最不靠谱,API文档上说:
The precision is not guaranteed – the Thread may sleep more or less than requested.
4. Alarm+Receiver方式,用于做长时间的timer。
Timer使用要注意,任何时候使用时都要考虑用户取消这个timer的实现;