![](/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.