在Android中的doinbackground()中执行UI任务

时间:2013-04-02 06:06:39

标签: android android-asynctask

有没有办法在AsyncTask的doinbackground()中执行UI任务。我很清楚在onPostExecute方法中做得更好。但在我的情况下,因为我需要使用可重复使用的警报,能够访问我的doinbackground中的UI将节省我很多时间。也就是说,我需要在46个地方调整代码,但是能够在doinbackground中执行此操作只需要在一个地方进行更改。

提前致谢

3 个答案:

答案 0 :(得分:27)

希望这能解决您的问题

    onPreExecute() {
       // some code #1
    }

    doInBackground() {
        runOnUiThread(new Runnable() {
                    public void run() {
                        // some code #3 (Write your code here to run in UI thread)

                    }
                });
    }

    onPostExecute() {
       // some code #3
    }

答案 1 :(得分:7)

除了从onPostExecute()更新用户界面外,还有两种更新用户界面的方法:

  1. 通过实施doInBackground()
  2. runOnUiThread()开始
  3. 来自onProgressUpdate()
  4. FYI,

    onProgressUpdate() - 每当您想要更新doInBackground()中的任何内容时,您只需使用publishProgress(Progress...)发布一个或多个进度单位,它就会onProgressUpdate() ping {{1}}更新UI线程。

答案 2 :(得分:3)

您可以使用onProgressUpdate而不是

Docs