How to delay execution android

旧时模样 提交于 2019-12-03 16:55:57

问题


I am building an android board game which features AI. The AI gets a turn and has to invoke a series of actions after which it posts invalidate to my custom view to update.

I need to slow down these actions so the user gets to see the AI having its turn rather than it flashing by.

I have tried something along these lines

    try {
        doFirstThing();
        Thread.sleep(500)
        //post invalidate

        doNextThing();
        Thread.sleep(1000)
        //post invalidate
     }
     catch (Exception e) {
     }

However this is having absolutely no effect. Also this is running in a separate thread if this wasn't obvious.

Whats my best option I've looked at handler but they don't need right as i need to execute a series of tasks in sequence updating the view each time.


回答1:


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



回答2:


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);


来源:https://stackoverflow.com/questions/14510709/how-to-delay-execution-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!