我们都知道我们可以在asyncTask中写一些异步的方法,是因为Android不允许在主线程(MainThread)中做网络访问等一些耗时的操作,但是我们也希望能在AsyncTask中更新UI操作怎么办呢,可以看看这篇:
http://stackoverflow.com/questions/23978400/how-to-update-ui-from-asynctask
简单说

onPreExecute()
runs before doInBackground()
onPostExecute()
runs after doInBackground() completes
onProgressUpdate()
this only runs when doInBackground() calls it with publishProgress()

于是我就在想如果说这是一个异步的线程,那么在MainThread外是不能够操作对UI进行处理的,那么为什么这三个方法能够操作呢,看一眼源码

/**     * Runs on the UI thread after {@link #publishProgress} is invoked.     * The specified values are the values passed to {@link #publishProgress}.     *     * @param values The values indicating progress.     *     * @see #publishProgress     * @see #doInBackground     */    @SuppressWarnings({"UnusedDeclaration"})    @MainThread    protected void onProgressUpdate(Progress... values) {    }

这个方法是一个空方法,最主要的是这个@MainThread注解(不懂注解的可以先学习一下java的注解),意思就是说这个方法将会运行在MainThread中,所以可以更改UI。MainThread也叫UIThread,关于这个有一个文章很好:
http://android-developers.blogspot.com/2009/05/painless-threading.html
(如果你404或者不喜欢英语)我简单解释一下就是说在Android中,应用已启动就会启动一个MainThread,MainThread如果阻塞5秒那么就会出现“application not responding ANR”,但是Android的UI是不线程安全的,所以如果你在workerthread(顾名思义)中操作UI可能会有bug,而且这个bug很难调试。

再一个就是,我们都知道onProgressUpdate方法会在publishProgress(Progress…)调用之后执行,publishProgress(Progress…)方法是可以写在workthread中的,那么UIThread是如何感知WorkerThread中的publishProgress(Progress…)方法呢,其实就是handler

AsyncTask runs the methods on the UI Thread by sending Runnables to the main thread Handler. This Handler takes every Runnable in the FIFO queue and run them after another sequentially with no parallelism. Thus if the disk-progress-state happens before online-progress-state, then the order of the publishProgress’s is preserved. The same applies to the order of publishProgress and onPostExecute.

可以参考:
http://stackoverflow.com/questions/17772595/use-asynctask-onprogressupdate-to-update-ui
就这么多,希望对你有用

更多相关文章

  1. Android Studio中genymotion安装方法
  2. Android使用HttpClient方法和易错问题
  3. Android开机自启动程序设置及控制方法思路浅谈
  4. android获取当前运行Activity名字的方法
  5. android画任意曲线时,去除移动过程中出现莫名直线的方法
  6. Android开发包下载(包括开发所需所有安装包的下载方法与地址)
  7. 一个编译时注解的 RxBus 库 - Apollo
  8. Android获取系统时间方法的总结

随机推荐

  1. 使用JQuery从外部文件中通过id选择器获取
  2. 使用jQuery更新textarea值更改的文本
  3. 是否每次都可能分离内容、表示和行为?
  4. jquery向Django后台发送数组
  5. 将JavaScript对象作为Dictionary 传递给C
  6. 如何防止缓存.NET JSON源
  7. 如何在用户选择操作后获取当前日期和时间
  8. jquery内部实现原理分析
  9. 用replaceWith()对DOM结点操作时应注意的
  10. JavaScript / jQuery:如何链接使用console