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

Lin*_*ncy 8 android android-asynctask

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

提前致谢

Sre*_*v R 28

希望这能解决你的问题

    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
    }
Run Code Online (Sandbox Code Playgroud)


Par*_*ani 7

除了更新UI之外onPostExecute(),还有两种更新UI的方法:

  1. doInBackground()实施runOnUiThread()
  2. onProgressUpdate()

仅供参考,

onProgressUpdate()- 每当您想要更新任何内容时doInBackground(),您只需要使用publishProgress(Progress...)发布一个或多个进度单元,它将ping onProgressUpdate()到UI线程上的更新.