[英]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.