[java] view plaincopy
public void showToast(String msg){
Looper.prepare();
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
Looper.loop();
}
只需要加上那两句就能在非UI线程中显示Toast
[java] view plaincopy
Toast里面的show()
public void show() {
...
service.enqueueToast(pkg, tn, mDuration); //把这个toast插入到一个队列里面
...
}
[java] view plaincopy
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 显示需要出现在一个线程的消息队列中.... 很隐蔽 |
|