等待publishProgress完成,然后继续执行doInBackground AsyncTask Android [英] Wait publishProgress finish before continue excute doInBackground AsyncTask android

查看:65
本文介绍了等待publishProgress完成,然后继续执行doInBackground AsyncTask Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的AsyncTask看起来像:

private class MyTask extends AsyncTask<String, Void, List<Data>> {
  private volatile UserData userData;
  protected List<Data> doInBackground(String... params) {
      // do some job 1
      publishProgress();
      // wait until the progress finish to update variable.
      if(userData!= null){
        //do some job 2
      }

      //do some job 3

  }

    protected void onProgressUpdate(Void... values) {
        // try to ask user and collect information
        userData= getData();
    }

}

问题是当我调用publishProgress()时,它仍然执行doInBackground中的作业3.我如何等待onProgressUpdate完成才能继续?

The problem is when I call publishProgress(), it still execute job 3 in doInBackground. How can I wait onProgressUpdate complete before continue?

更新:
在getData()方法中,我尝试获取用户的当前位置,该位置无法在doInBackground和视图中的其他信息中使用.我必须这样做,因为作业1需要很长时间,并且可以更改用户的当前位置.我需要用户的最准确的位置.

Update:
In the getData() method, I tried to get the current location of user, which can't work in doInBackground and some other information from the view. I have to do this cause the job 1 take a very long time, and the current location of user can be changed. I need the most exactly location of user.

推荐答案

我认为,您使用doInBackground和publishProgress()的方式有误,但是我仍然需要查看方法 getData()的代码.

I think, the way you are using doInBackground and publishProgress() is something wrong, but still I need to see the code of method getData() .

doInBackground 方法执行某些任务,该任务应该在事件线程以外的其他线程中执行,而在 publishProgress 方法中,您应该执行与事件线程.因此,如果 getData()与事件线程无关,请在 doInBackground 中编写代码.

doInBackground method should be used to do some task, which should be executed in other thread than event thread, and in publishProgress method, you should execute tasks which works with event thread. So, if getData() has nothing to do with event thread, please write the code in doInBackground itself.

但是,如果您的要求只是同时使用这两种方法,则可以添加一个同步块,如下所示:

However, if your requirements are just use both these methods, as present, then you can add a synchronize block, as like below:

private class MyTask extends AsyncTask<String, Void, List<Data>> {
  private volatile UserData userData;
  protected List<Data> doInBackground(String... params) {

  synchronize(userData)
  {
      // do some job 1
      publishProgress();
      // wait until the progress finish to update variable.
      if(userData!= null){
        //do some job 2
      }

      //do some job 3
    }
  }

    protected void onProgressUpdate(Void... values) {
        // try to ask user and collect information
        synchronize(userData)
        {
            userData= getData();
        }
    }

}

这篇关于等待publishProgress完成,然后继续执行doInBackground AsyncTask Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆