码迷,mamicode.com
首页 > 移动开发 > 详细

Android在非UI线程中显示Toast

时间:2014-11-03 12:48:51      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:android   style   blog   http   io   ar   java   sp   strong   

  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

Android在非UI线程中显示Toast

标签:android   style   blog   http   io   ar   java   sp   strong   

原文地址:http://www.cnblogs.com/jita/p/3171530.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!