使用AsyncTask引发RuntimeException:sending message to a Handler on a dead thread

报错出现在onPost方法的调用,从字面意思理解,明显是线程更新界面的问题
在网上找了找,找到答案,原来是Android Framework本身的Bug, 要修正也很简单,就是在你的App主Activity的onCreate()中加入如下代码:

<span style="font-family: Arial, Helvetica, sans-serif; background-color: rgb(255, 255, 255);"></span><pre name="code" class="java">public void onCreate() { 
try {
          // 这个的作用就是将 AsyncTask初始化到主线程
          Class.forName("android.os.AsyncTask"); 
} catch (ClassNotFoundException e) {

}

super.onCreate();
}

查看到源码解释如下

There are a few threading rules that must be followed for this class to work properly:
The task instance must be created on the UI thread.
execute(java.lang.Object[]) must be invoked on the UI thread.
Do not call onPreExecute(), onPostExecute(java.lang.Object), doInBackground(java.lang.Object[]), onProgressUpdate(java.lang.Object[]) manually.
The task can be executed only once (an exception will be thrown if a second execution is attempted.)

原来AsyncTask必须在UI线程调用,因为低版本的Handler是静态的,而AsyncTask实质还是调用Handler,若在异步线程中实例化,

必然使AsyncTask最后调用异步线程的Handler,而调用onPost的时候异步线程已经被销毁,于是就报以上错误。

解决方法也就变的很简单了,或者UI线程实例化Task对象,或者就按照如上方法预先加载AsyncTask类


<p>高版本中的api对此的补救方式也很明显</p><p></p><pre name="code" class="java"> /** @hide Used to force static handler to be created. */
    public static void init() {
        sHandler.getLooper();
    }

通过系统调用hide的init方法,让Handler绑定到UI线程

 



                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值