在Android UI線程中執行定時任務的方法,androidui線程執行

來源:互聯網
上載者:User

在Android UI線程中執行定時任務的方法,androidui線程執行

         在項目中,我們經常會碰見執行定時任務的情況,比如下面這個情境:在2秒內連續點擊兩次返回鍵,應用就退出。這個功能實現的思路大體這樣:定義一個類變數goback,記錄點擊的次數,如果2秒內點擊了2次就finish,如果沒有,goback就被重設為0,其中一種實現方法如下(1.0):

<span style="white-space:pre"></span>new Handler().postDelayed(new Runnable() {@Overridepublic void run() {goback = 0;}}, 2000);
接下來,我再探討一下其他實現上面功能的方法:

1.1使用 ScheduledExecutorService

private static final ScheduledExecutorService worker =   Executors.newSingleThreadScheduledExecutor();  Runnable task = new Runnable() {    public void run() {      /* Do something… */    }  worker.schedule(task, 2, TimeUnit.SECONDS);

1.2 使用Timer類

new Timer().schedule(new TimerTask() {              @Override    public void run() {        // this code will be executed after 2 seconds           }}, 2000);

1.3還是使用handler,不過增加了message的發送

Handler myHandler = new DoSomething();Message m = new Message();m.obj = c;//passing a parameter heremyHandler.sendMessageDelayed(m, 1000);class DoSomething extends Handler {        @Override        public void handleMessage(Message msg) {          MyObject o = (MyObject) msg.obj;          //do something here        }    }

1.4最後一種使用Thread類,有點繁瑣,不建議用

private static long SLEEP_TIME = 2 // for 2 second..MyLauncher launcher = new MyLauncher();            launcher.start();..private class MyLauncher extends Thread {        @Override        /**         * Sleep for 2 seconds as you can also change SLEEP_TIME 2 to any.          */        public void run() {            try {                // Sleeping                Thread.sleep(SLEEP_TIME * 1000);            } catch (Exception e) {                Log.e(TAG, e.getMessage());            }            //do something you want to do           //And your code will be executed after 2 second        }    }

差不多就是以上五種做法,各有各的適用情境,代碼比較簡單,不多說,直接拿過去用就行。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.