Andriod學習筆記(12)—關於Timer的使用例子

來源:互聯網
上載者:User

1、Timer的使用主要是為了到達倒計時的作用

見代碼:

Timer timer = new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {// TODO Auto-generated method stubMessage msg = new Message();msg.what = Hor_Translate;handler.sendMessage(msg);// System.out.println("send message");}}, 0, 50);//0代表第一次延時0秒開始執行,50代表每隔50毫秒迴圈執行一次handler = new Handler() {public void handleMessage(Message msg) {// 要做的事情switch (msg.what) {case 1:// 執行break;case 2:                                         // 執行break;}super.handleMessage(msg);}};

2、取消一個倒計時

timer.cancel();

3、參數說明:

             new Timer().schedule(new TimerTask(){             @Override             public void run() {             // TODO Auto-generated method stub             // do some your own process when the timeout come up            }}, delay, period);

Timer作用:延時或迴圈執行。

使用帶period參數的schedule方法該timer以period為周期,迴圈執行run方法。--------迴圈執行。

使用不帶period參數的schedule方法則該timer只在delay時間到來時執行一次。--------單次執行。


另:TimerTask運行在一個單獨的線程裡,而不是UI線程。所以使用android timer時,注意android的單線程原則,確保安全執行緒。不要在TimerTask的run方法中做UI相關的操作,如:TextView.setText()等,這樣可能會導致UI線程阻塞。如果需要可以使用handler向UI線程發訊息,具體處理由UI線程自己完成。在使用完Timer之後,要使用Timer的cancel方法取消Timer,否則Timer一直在運行。

4、Timer和Thread都可使用Handle,關於Thread:http://blog.csdn.net/moruna/article/details/7835442

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.