Last Updated: February 25, 2016
·
415
· zhlwish

Delay execution in Android

We want do something later sometimes, usually we implement it using Timer, however, we can use Hanlder to do it easily.

protected final void doSomething() {
    // do some thing here
}

protected final void doSomething(long duration) {
    Message msg = Message.obtain(mHandler, DO_SOMETHING);
    mHandler.sendMessageDelayed(msg, duration);
}

protected Handler mHandler = new Handler() {

    @Override
    public void handleMessage(Message msg) {
        if (msg.what == DO_SOMETHING) {
            doSomething();
        }
    }
};