[英]ProgressDialog.setMessage(String) doesn't throw IllegalStateException
我在以下代碼中從工作線程調用Progressdialog.setMessage(String)
方法,但是Android不會拋出IllegalStateException
,該IllegalStateException
應該顯示為“ java.lang.IllegalStateException:在UI線程之外的其他線程上調用View方法”,因為我正在修改來自Android禁止的UI線程外部的UI。
這是我的工作線程作為內部類的可運行對象:
public class HostOnHoldRunnable implements Runnable {
@Override
public void run() {
hostOnHoldDialog.setMessage("Game is on hold because the host paused the app (" + currentTimeLeftForHostOnHoldTimeOut / 1000 + ")");
}
}
}
注意:hostOnHoldDialog是我的Activity的ProgressDialog
成員。
android不會根據消息更新UI,而不會IllegalStateException
。
這是錯誤嗎?
如果我在Runnable
使用runOnUiThread,則一切正常,例如
public class HostOnHoldRunnable implements Runnable {
@Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
hostOnHoldDialog.setMessage("Game is on hold because the" +
" host paused the app (" +
currentTimeLeftForHostOnHoldTimeOut / 1000 + ")");
}
});
}
}
嘗試使用
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
hostOnHoldDialog.setMessage("Game is on hold because the host paused the app (" + currentTimeLeftForHostOnHoldTimeOut / 1000 + ")");
}
});
嗯,您會看到Handler
與Looper
一起運行消息,該Handler在UI線程上運行,每個View都有一個附加的處理程序,使它可以在UI線程,任何新創建的想要運行消息的Thread上張貼方法/函數。或在UI線程上運行必須調用Handler或Looper.prepare(),稍后將實現該處理器。 在多線程應用程序上,使用Handler()。post()或Handler()。postDelayed()或View.post()或View.postDelayed()或Context.getMainLooper()都是可以幫助您完成以下任務的函數在UI線程上發布,因此,如果您使用這種方法調用方法,則不會獲得異常。 因此這里沒有問題或錯誤,只需閱讀關於Looper,Hanlder和View的文檔的幾行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.