开发者

How to 'flush' UI Thread actions before continue execution

开发者 https://www.devze.com 2023-04-08 07:46 出处:网络
I\'ve got a problem in Android with runOnUiThread. I start an AsyncTask (inside an Activity) that waits for a while, and after calls the method showDialog(id). After this call, it sleeps for another w

I've got a problem in Android with runOnUiThread. I start an AsyncTask (inside an Activity) that waits for a while, and after calls the method showDialog(id). After this call, it sleeps for another while, and finishes calling the method dismissDialog(id).

This is the code:

public class MyActivity extends Activi开发者_Python百科ty {

...

    protected class StartWaiting extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                Thread.sleep(2500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // Show dialog
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showDialog(PROGRESS_DIALOG_LOADING);
                }
            });

            try {
                Thread.sleep(2500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // Dismiss dialog
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dismissDialog(PROGRESS_DIALOG_LOADING);
                }
            });

            return null;
        }

        @Override
        protected void onPostExecute(Void arg) {
            new StartServices().execute();
        }
    }

}

Unfortunately, the behaviour is different from what I want to do: showDialog() and dismissDialog() are called one immediately after the other.

I think that the reason why this happens is that the UI Thread execute both actions "when it can", that is at the end of sleeping actions.

Well, does it exist some "flushUI()" method that force a thread (in this case, the UI Thread) to execute every action before continue?


You could just add a synchronization point in your thread, using a CountDownLatch for instance:

        final CountDownLatch latch = new CountDownLatch(1);

        view.post(new Runnable() {
            public void run() {
                try {
                    // Do stuff on the UI thread
                } finally {
                    latch.countDown();
                }
            }
        });

        try {
            if (!latch.await(CAPTURE_TIMEOUT, TimeUnit.MILLISECONDS)) {
                return;
            }
        } catch (InterruptedException e) {
            // Handle exception
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号