Android在非UI线程中显示Toast

来源:互联网 发布:火箭nba 知乎 编辑:程序博客网 时间:2024/05/23 20:23

做个android开发的都知道,在子线程中是不允许进行UI更新。如果要进行更新必须在消息队列中

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

Looperpublic 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(); }参考文档:http://blog.csdn.net/xiaanming/article/details/8904645
0 0