How to delay execution android

雨燕双飞 提交于 2019-12-03 06:05:56

Using a Handler, which is a good idea if you are executing from a UI thread...

    final Handler h = new Handler();

    final Runnable r2 = new Runnable() {

        @Override
        public void run() {
            // do second thing
        }
    };

    Runnable r1 = new Runnable() {

        @Override
        public void run() {
            // do first thing
            h.postDelayed(r2, 10000); // 10 second delay
        }
    };

    h.postDelayed(r1, 5000); // 5 second delay

Just to add a sample : The following code can be executed outside of the UI thread. Definitely, Handler must be use to delay task in Android

Handler handler = new Handler(Looper.getMainLooper());
final Runnable r = new Runnable() {
    public void run() {
        //do your stuff here after DELAY milliseconds
    }
};
handler.postDelayed(r, DELAY);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!