错误使用AsyncTask导致UI处理出错

■■ 想做的效果是

     1.显示Loading画面

     2.然后异步在后台访问远程信息

     3.返回远程信息后,关闭Loading画面. 如果有错误,显示错误对话框.

 

在实现最初,所有处理都放到了AsyncTask的doInBackground()中,在显示对话框时出异常:

  Android Can't create handler inside thread that has not called Looper.prepare()

 

图得省事,使用了网上说的方法:

     Looper.prepare();

     显示对话框

     Looper.loop();

 

貌似好用了.

 

■■ 结果这两天发现画面经常有假死的情况

最终在stackoverflow上找到解决方法

 

     1. doInBackground()

         这里面只负责处理数据部分,UI的处理不要放在这里.

 

     2. onPostExecute()

         这里才是处理结果的地方,且是运行在UI线程下,不需要做其它处理.

 

难怪之前使用得怪怪的,我有的地方放在onPostExecute() 里,有的地方就是图省事放到了doInBackground()中,

我还奇怪不是在所有的地方都有这个现象呢.

 

 

■■ 刚才查了一下API文档,后悔当初没早点看就开始使用网上的例子,

    人家文档写的清楚清楚啊, 555555555555

 

----------------------------------------------------------------------------------------------------------------------------

  1. onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.
  2. doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.
  3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.
  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值