定义变量:
private final int TIMEID = 1000; private Timer m_timer = null; private TimerTask m_timerTask = null; private Handler m_timerHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch(msg.what) { case TIMEID: onTimer(msg.what); break; } } };
onTimer()就是定时去执行的函数,可直接定义;
开启关闭定时器函数:
private void startMyTimer() { stopMyTimer(); m_timerTask = new TimerTask() { @Override public void run() { // 需要做的事:发送消息 Message message = m_timerHandler.obtainMessage(TIMEID); m_timerHandler.sendMessage(message); } }; m_timer= new Timer(); m_timer.schedule(m_timerTask,10, 10); } private void stopMyTimer() { if(m_timer != null) { m_timer.cancel(); m_timer = null; } if(m_timerTask != null) { m_timerTask.cancel(); m_timerTask = null; } }