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中看到如下:
也就是说普通线程中不能直接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();
经查看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();
相关文章推荐
- Android Studio使用lambda
- Android概述
- Android开发艺术探索—— 第十一章Android的线程和线程池
- Android listview子控件的的点击事件
- android图片加载与缓存
- android中的AIDL
- Mac、Windows下Android Studio快捷键的使用
- 给 Android 开发者的 RxJava 详解
- ViewHolder重用机制 RecyclerView+CardView 优化
- android反编译工具Apktool安装与使用
- 给 Android 开发者的 RxJava 详解
- android模拟器无法使用camera拍照
- Android SDK 在线更新镜像服务器资源
- Android使用 DrawerLayout实现侧滑
- Android自定义ViewPager指示器
- android studio <item/>标签下不能使用showAsAction属性
- Android studio 使用JitPack发布library到Github开源库
- 仿网易云音乐Android端歌手资料页面的实现
- android调试输出log打印信息到本地文件
- 【Android学习笔记】Android中View的事件分发机制