[英]Handler or runOnUiThread solution for “Can't create handler inside thread that has not called Looper.prepare() ”
Recently, I show up a toast in user thread and got the above runtime error. 最近,我在用户线程中出现了一个toast并得到了上面的运行时错误。
From Can't create handler inside thread that has not called Looper.prepare() , they proposed use Handler
as solution. 从无法在未调用Looper.prepare()的线程内创建处理程序 ,他们建议使用
Handler
作为解决方案。 However, I saw the solution is quite lengthy and cumbersome. 但是,我看到解决方案非常冗长和繁琐。
My own solution is to use runOnUiThread
我自己的解决方案是使用
runOnUiThread
private void showTooDarkToastMessage()
{
((Activity) this.getContext()).runOnUiThread(new Runnable() {
@Override
public void run() {
Toast toast = Toast.makeText(getContext(), getResources().getString(R.string.toast_toodark), Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
});
}
I was wondering, is there any shortcoming of using runOnUiThread
, compared to Handler
? 我想知道,与
Handler
相比,使用runOnUiThread
有什么缺点吗?
Because you are showing a UI element (a Toast message) runOnUiThread is perfect. 因为您正在显示UI元素(Toast消息),所以runOnUiThread是完美的。
A Handler will run its task on the specified thread. Handler将在指定的线程上运行其任务。 For instance,
例如,
protected void onCreate( Bundle savedInstanceState )
{
Handler hander = new Handler();
//Create thread, post to handler
}
would create a new Handler that would run its posts on the UI thread. 将创建一个新的Handler,它将在UI线程上运行其帖子。 calling Activiy.runOnUiThread just posts the runnable specifically to the UI thread.
调用Activiy.runOnUiThread只是将runnable专门发布到UI线程。 By default, Handlers will run on whatever thread they were created in. The above code would work identical to using runOnUiThread because the onCreate method is run on the UI thread!
默认情况下,处理程序将在它们创建的任何线程上运行。上面的代码与使用runOnUiThread相同,因为onCreate方法在UI线程上运行!
Handlers would be preferred if you needed to communicate between multiple background threads. 如果您需要在多个后台线程之间进行通信,则首选处理程序。
Because mobile devices have limited resources, work run on the UI thread should be kept relatively light. 由于移动设备的资源有限,因此在UI线程上运行的工作应保持相对较轻。 Intense work done on the UI thread can cause Application Not Responding (ANR) errors and can cause the OS to kill your process.
在UI线程上进行的大量工作可能导致应用程序无响应(ANR)错误,并可能导致操作系统终止您的进程。
Actually runOnUiThread()
using Handler
inside. 实际上
runOnUiThread()
使用Handler
里面。 So, there is no downsides to use runOnUiThread()
if you want to simple post some job to do in the UI Thread. 因此,如果您想简单地在UI线程中发布一些工作,那么使用
runOnUiThread()
没有任何缺点。
If you are interesting in difference between Handler
and runOnUiThread()
you can read about it in this answer 如果你对
Handler
和runOnUiThread()
之间的区别感兴趣,你可以在这个答案中阅读它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.