[java]
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
[java]
Toast裡面的show()
public void show() {
...
service.enqueueToast(pkg, tn, mDuration); //把這個toast插入到一個隊列裡面
...
}
Toast裡面的show()
public void show() {
...
service.enqueueToast(pkg, tn, mDuration); //把這個toast插入到一個隊列裡面
...
}
[java]
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 顯示需要出現在一個線程的訊息佇列中.... 很隱蔽