您的位置:首页 > 移动开发 > Android开发

android之子线程中的Toast

2016-05-21 17:32 411 查看
一直以来都在service和activity中运用过Toast,对于消息的提醒提供了极大地方便。今天在进行代码调试的时候,为了效果无意在线程中使用了Toast,结果却报错了,这让我是木有想到的,看来还是基础太差啊!

  经查看Toast的源码,终于搞懂了。

1,关键位置在于Toast初始化的时候:

public class Toast {
final Handler mHandler = new Handler();
.............................................................
}
2.而在handler中看到如下:
public Handler(Callback callback, boolean async) {
if (FIND_POTENTIAL_LEAKS) {
final Class<? extends Handler> klass = getClass();
if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
(klass.getModifiers() & Modifier.STATIC) == 0) {
Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
klass.getCanonicalName());
}
}

mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
}


也就是说普通线程中不能直接new一个handler
3,而在looper中

/**
* Return the Looper object associated with the current thread. Returns
* null if the calling thread is not associated with a Looper.
*/
public static @Nullable Looper myLooper() {
return sThreadLocal.get();
}子线程也是普通线程,由此看出普通线程ThraedLocal中没有设置looper,所以会抛出异常;

解决办法:

new Thread(){

public void run() {

Log.i("log", "run");

Looper.prepare();

Toast.makeText(ActivityTestActivity.this, "toast", 1).show();

Looper.loop();// 进入loop中的循环,查看消息队列

};

}.start();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: