[英]What is the best way to wait until a runnable on the main thread completes in Android?
我需要從WebViewClient#shouldInterceptRequest
內部的用戶那里收集用戶名和密碼,因此必須阻止WebView
IO線程,直到用戶在主線程上提供用戶名和密碼為止。 等待可運行項目完成的最佳方法是什么?
我當前最喜歡的方式是(為簡潔起見,省略了異常和超時):
final CountDownLatch countDownLatch = new CountDownLatch(1);
new Handler(Looper.getMainLooper()).post(new Runnable() {
public void run() {
callSomethingWithAsyncCallback(new Runnable() {
public void run() {
countDownLatch.countDown();
}
});
}
});
countDownLatch.await();
使用ExecutorService
的東西似乎更好,因為我可以簡單地使用Future#get
進行阻止。 然而,沒有ExecutorService
主線程上運行,並使用一個從Executors
只是主線程似乎浪費反彈嗎。 有什么想法嗎?
請使用AsyncTask而不是可運行的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.