- public void showToast(String msg){
- Looper.prepare();
- Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
- Looper.loop();
- }
public void showToast(String msg){
Looper.prepare();
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
Looper.loop();
}
只需要加上那两句就能在非UI线程中显示Toast
- Toast里面的show()
- public void show() {
- ...
- service.enqueueToast(pkg, tn, mDuration); //把这个toast插入到一个队列里面
- ...
- }
Toast里面的show()
public void show() {
...
service.enqueueToast(pkg, tn, mDuration); //把这个toast插入到一个队列里面
...
}
- Looper
- public static final void prepare() {
- if (sThreadLocal.get() != null) {
- throw new RuntimeException("Only one Looper may be created per thread");
- }
- sThreadLocal.set(new Looper()); //在当前线程中创建一个Looper
- }
- private Looper() {
- mQueue = new MessageQueue(); //关键在这,创建Looper都干了什么。 其实是创建了消息队列
- mRun = true;
- mThread = Thread.currentThread();
- }
Looper
public static final void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper()); //在当前线程中创建一个Looper
}
private Looper() {
mQueue = new MessageQueue(); //关键在这,创建Looper都干了什么。 其实是创建了消息队列
mRun = true;
mThread = Thread.currentThread();
}
总结下:Toast 显示的必要条件:
1:Toast 显示需要出现在一个线程的消息队列中.... 很隐蔽
原文地址:http://blog.csdn.net/xiaanming/article/details/8904645
补充:在调用了Looper.loop(); 之后,似乎会让整个线程停止,不太懂,还应该再做了解