错误使用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.

 

 

 

你可能感兴趣的:(UI,android,AsyncTask)