1. public void showToast(String msg){  
  2.         Looper.prepare();  
  3.         Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();  
  4.         Looper.loop();  
  5.     }  
public void showToast(String msg){
		Looper.prepare();
		Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
		Looper.loop();
	}

只需要加上那两句就能在非UI线程中显示Toast

  1. Toast里面的show()  
  2.     public void show() {  
  3.       ...  
  4.         service.enqueueToast(pkg, tn, mDuration);   //把这个toast插入到一个队列里面   
  5.         ...  
  6.     }  
Toast里面的show()
    public void show() {
      ...
        service.enqueueToast(pkg, tn, mDuration);   //把这个toast插入到一个队列里面
        ...
    }

 

  1. Looper  
  2. public static final void prepare() {  
  3.         if (sThreadLocal.get() != null) {  
  4.             throw new RuntimeException("Only one Looper may be created per thread");  
  5.         }  
  6.        sThreadLocal.set(new Looper());  //在当前线程中创建一个Looper   
  7.     }  
  8.   
  9. private Looper() {  
  10.         mQueue = new MessageQueue();  //关键在这,创建Looper都干了什么。 其实是创建了消息队列   
  11.         mRun = true;  
  12.         mThread = Thread.currentThread();  
  13.     }  
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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-11
  • 2022-12-23
  • 2022-12-23
  • 2021-12-15
  • 2022-02-05
  • 2022-12-23
猜你喜欢
  • 2021-08-13
  • 2021-10-18
  • 2021-09-04
  • 2022-02-19
  • 2021-11-29
  • 2022-01-27
相关资源
相似解决方案