![](/img/trans.png)
[英]How to pause the thread for some time and then show the UI once user interacts, continue the thread execution
[英]How to 'flush' UI Thread actions before continue execution
我在Android中使用runOnUiThread遇到了问题。 我启动一个AsyncTask(在Activity中),等待一会儿,然后调用showDialog(id)方法。 调用之后,它会再睡眠一会,并完成调用方法dismissDialog(id)。
这是代码:
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();
}
}
}
不幸的是,该行为与我要执行的操作不同:showDialog()和dismissDialog()在另一个之后立即被调用。
我认为发生这种情况的原因是,UI线程“在可能的情况下”执行两个动作,即在睡眠动作结束时执行。
那么,是否存在一些“ flushUI()”方法来强制线程(在这种情况下为UI Thread)在继续之前执行每个操作?
您可以使用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.