简体   繁体   English

如何在继续执行之前“刷新” UI线程操作

[英]How to 'flush' UI Thread actions before continue execution

I've got a problem in Android with runOnUiThread. 我在Android中使用runOnUiThread遇到了问题。 I start an AsyncTask (inside an Activity) that waits for a while, and after calls the method showDialog(id). 我启动一个AsyncTask(在Activity中),等待一会儿,然后调用showDialog(id)方法。 After this call, it sleeps for another while, and finishes calling the method dismissDialog(id). 调用之后,它会再睡眠一会,并完成调用方法dismissDialog(id)。

This is the code: 这是代码:

public class MyActivity extends Activity {

...

    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. 不幸的是,该行为与我要执行的操作不同:showDialog()和dismissDialog()在另一个之后立即被调用。

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. 我认为发生这种情况的原因是,UI线程“在可能的情况下”执行两个动作,即在睡眠动作结束时执行。

Well, does it exist some "flushUI()" method that force a thread (in this case, the UI Thread) to execute every action before continue? 那么,是否存在一些“ flushUI()”方法来强制线程(在这种情况下为UI Thread)在继续之前执行每个操作?

You could just add a synchronization point in your thread, using a CountDownLatch for instance: 您可以使用CountDownLatch例如在线程中添加一个同步点:

        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
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM