Android:从AsyncTask doInBackground方法调用UI线程上的方法

16

我正在使用AsyncTask将数据上传到UI。我编写了从服务器下载数据的代码,并在单独的方法中调用该方法来执行doInBackground。但是,由于在doInBackground中无法访问UI方法,因此将会出现错误。请问有没有其他替代方法可以在doInBackground中访问UI方法?

4个回答

48

有没有其他方法可以从doinBackground访问UI方法?

doInBackground()中调用publishProgress()。将更新UI的逻辑放在您的AsyncTaskonProgressUpdate()中。在调用publishProgress()之后,onProgressUpdate()将在主应用程序线程(即UI线程)上调用。 这里是一个演示该过程的样例项目


14
CommonsWare这个名字已经足够了。+1。 - Chirag
我知道runOnUiThread()的方法,但喜欢另一种处理方式+1。 - Deva
嗨,我在链接中找到了很好的答案。非常感谢你。 - balu...

8

你好,我能在doInBackground中调用runOnUiThread()吗?这样会起作用吗?或者像往常一样,我可以在onCreate中调用runOnUiThread吗?我有一个疑问,使用runOnUiThread上传数据时会阻塞UI吗? - balu...
只有在doInBackground()中调用它时才有意义,否则它就没有意义。 - ngesh
你必须在更新主UI的地方编写runOnUIThread。 - Chirag

3

只将 doInBackground() 用于以下任务:

  1. 需要一定时间的任务
  2. 与UI无关的任务

然后,您可以实现 AsyncTask.onPostExecute() 来在主UI线程上运行代码以处理来自AsyncTask的结果

AsyncTask.onPostExecute() 的JavaDoc中获得:

"在 doInBackground 后在UI线程上运行... "


1
正如其他人所指出的那样,您可以使用runOnUiThread。但是,在doInBackground中这样做似乎有点奇怪。如果您想向用户指示进度,则应在AsyncTask.onProgressUpdate中处理该进度,并在doInBackground中调用publishProgress。
您可以在此处阅读有关AsyncTask的更多信息:http://developer.android.com/reference/android/os/AsyncTask.html -Dan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接