java.lang.RuntimeException: Can't create handler

调用 handler 使用报错java.lang.RuntimeException: Can't create handler inside thread that has not called Looperjava


在你的类中加
android

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();StrictMode.setThreadPolicy(policy);

和在你的ManiFestFile中加:ide

<uses-permission android:name="android.permission.INTERNET"/>


调用Looper.prepare()启用Looper后执行
函数


介绍:oop

Toast和Looper。Handler消息循环机制。ui


(1) Looper类别用来为一个线程开启一个消息循环。默认状况下Android中新诞生的线程是没有开启消息循环的。(主线程除外,主线程系统会自动为其建立Looper对象,开启消息循环)
Looper对象经过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个MessageQueue。


(2) 一般是经过Handler对象来与Looper交互的。Handler可看作是Looper的一个接口,用来向指定的Looper发送消息及定义处理方法。
默认状况下Handler会与其被定义时所在线程的Looper绑定,好比,在主线程中定义,其是与主线程的Looper绑定。
mainHandler = new Handler() 等价于new Handler(Looper.myLooper()).
Looper.myLooper():Return the Looper object associated with the current thread 获取当前进程的looper对象。
还有一个相似的 Looper.getMainLooper() 用于获取主线程的Looper对象。

(3) 在非主线程中直接new Handler() 会报以下的错误:
E/AndroidRuntime( 6173): Uncaught handler: thread Thread-8 exiting due to uncaught exception
E/AndroidRuntime( 6173): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
缘由是非主线程中默认没有建立Looper对象,须要先调用Looper.prepare()启用Looper。
 
(4) Looper.loop(); 让Looper开始工做,从消息队列里取消息,处理消息。
注意:写在Looper.loop()以后的代码不会被执行,这个函数内部应该是一个循环,当调用mHandler.getLooper().quit()后,loop才会停止,其后的代码才能得以运行。
 
(5) 基于以上知识,可实现主线程给子线程(非主线程)发送消息。spa

相关文章
相关标签/搜索