簡體   English   中英

等待Android主線程中的可運行程序完成之前的最佳方法是什么?

[英]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而不是可運行的。

  • AsyncTask在另一個線程內的doInBackground()中執行所有操作,該線程無法訪問您的視圖所在的GUI。
  • preExecute()和postExecute()使您可以在此新線程發生繁重之前和之后訪問GUI,您甚至可以將long操作的結果傳遞給postExecute(),然后顯示任何處理結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM