Toast.makeText(mContext, "msg", Toast.LENGTH_SHORT).show();
在子线程里创建 Toast
时出现报错:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare().
在没有调用Looper.prepare()
的线程里,无法创建handler
。
原因是修改 UI 需要在主线程里。
1. Thread
因为线程需要 Looper
来循环处理消息,但是子线程中默认是没有 Looper
的,查看一下 Looper
的源码,类注释如下:
/**
* Class used to run a message loop for a thread. Threads by default do
* not have a message loop associated with them; to create one, call
* {@link #prepare} in the thread that is to run the loop, and then
* {@link #loop} to have it process messages until the loop is stopped.
*
* <p>Most interaction with a message loop is through