简体   繁体   English

Android在运行asynctasks之间交换数据

[英]Android exchange data between running asynctasks

What i am trying to achieve is share data between running asynctask (doInBackground). 我想要实现的是在运行asynctask(doInBackground)之间共享数据。 So whats happening is that i have separate class (extends Asynctask) that loads data and activity with its own Async class which i use to update info in the activity. 所以发生的事情是我有单独的类(扩展Asynctask),它使用自己的Async类加载数据和活动,我用它来更新活动中的信息。 Basicly what i am trying to achieve is the thread in the activity (monitoring thread) to work alongside with the loader and providing some data from the loader class and when the loader is ready both the "monitoring" and the "loader" should die. 基本上我想要实现的是活动中的线程(监视线程)与加载器一起工作并从加载器类提供一些数据,当加载器准备就绪时,“监视”和“加载器”都应该死掉。

I tried having a volatile variable which I set using interfaces, but no success i cant seem to be able to share information between the threads(asynctasks).. Any suggestions? 我尝试使用接口设置的volatile变量,但没有成功我似乎无法在线程之间共享信息(asynctasks)..有什么建议吗? Maybe an Exchanger class is needed? 也许需要一个Exchanger课程?

Any reason you can't use the onProgressUpdate functionality? 你有什么理由不能使用onProgressUpdate功能吗? I may be confused by your use case... but an example might be the following: 我可能会对你的用例感到困惑......但是一个例子可能如下:

class MyActivity extends Activity {

  private AsyncTask<Uri,MyDataObject, MyResult> = new AsyncTask<Uri,MyDataObject, MyResult>() {
    private MyResult mResult;

    protected MyResult doInBackground(Uri... uris) {           
      int count = urls.length;
      mResult = new MyResult()

      for (int i = 0; i < count; i++) {
        MyDataObject anObject = mDataLoader.getObject(uris[i]);
        publishProgress(anObject);

        mResult.add(anObject);
        // Escape early if cancel() is called
        if (isCancelled()) break;
      }
      return totalSize;
    }

    protected void onProgressUpdate(MyDataObject... data) {
      addDataToUI(data[0]);
    }

    protected void onPostExecute(MyResult result) {
      Toast.makeText("All Done!", Toast.LENGTH_LONG).show();
    }
  }
}

It sounds like you want to have the Activity show some information as the data is loaded by the loader thread? 听起来你想让Activity显示一些信息,因为数据是由加载器线程加载的? So you need to pass some information from the loader into the Activity, updating the UI. 因此,您需要将一些信息从加载器传递到Activity,更新UI。 In this case I'm not sure you need a second AsyncTask (and associated thread) in the Activity, as you still need to get the data to the main thread before you can update the UI. 在这种情况下,我不确定在Activity中是否需要第二个AsyncTask(和关联的线程),因为在更新UI之前仍需要将数据提供给主线程。 Instead, you should do as JRaymond suggests and just push the changes to the main thread using publishProgress and handle them on the main thread in onProgressUpdate 相反,你应该按照JRaymond的建议做,只需使用publishProgress将更改推送到主线程,并在onProgressUpdate的主线程上处理它们

If you need something more general, you could also consider using java.util.concurrent. 如果你需要更通用的东西,你也可以考虑使用java.util.concurrent。 For example, a BlockingQueue can be used to implement the consumer/producer pattern. 例如,BlockingQueue可用于实现消费者/生产者模式。 See the Javadoc for a code snippet . 请参阅Javadoc以获取代码段

All async tasks (unless executed with the executor provided) run on the same background thread, so it is not possible to execute them concurrently. 所有异步任务(除非使用提供的执行程序执行)都在同一后台线程上运行,因此无法同时执行它们。

From documentation: 来自文档:

When first introduced, AsyncTasks were executed serially on a single background thread. 首次引入时,AsyncTasks在单个后台线程上串行执行。 Starting with DONUT, this was changed to a pool of threads allowing multiple tasks to operate in parallel. 从DONUT开始,这被改为一个线程池,允许多个任务并行运行。 Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution. 从HONEYCOMB开始,任务在单个线程上执行,以避免由并行执行引起的常见应用程序错误。

If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR. 如果您真的想要并行执行,可以使用THREAD_POOL_EXECUTOR调用executeOnExecutor(java.util.concurrent.Executor,Object [])。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM