Android AsyncTask - 执行顺序 [英] Android AsyncTask - Order of execution

查看:13
本文介绍了Android AsyncTask - 执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了有关 AsyncTasks 执行顺序的问题.

I am facing an issue regarding the order of exection of AsyncTasks.

我的问题是:

假设我有 2 个 AsyncTask 实现:MyAsyncTask1MyAsyncTask2

Assuming I have 2 implementations of AsyncTask : MyAsyncTask1 and MyAsyncTask2

以下列方式调用:

new MyAsyncTask1 ().execute ();
new MyAsyncTask2 ().execute ();

是否保证 MyAsyncTask1MyAsyncTask2 之前执行?有一点是肯定的,它们不会并行执行,因为使用了默认执行器,即 SERIAL_EXECUTOR.问题在于执行顺序:先执行哪个??

Is it garanteed that MyAsyncTask1 is executed before MyAsyncTask2 ? One thing for sure, they are not executed in parallel since the default executor is used, which is SERIAL_EXECUTOR. The problem lies in the order of execution : which will be executed first ??

如果执行顺序未确定,我如何强制执行 AsyncTasks 的执行顺序??

If the order of execution is not determined, how can I enforce an order of execution for the AsyncTasks ??

我需要的是在 MyAsyncTask2 之前执行 MyAsyncTask1,但情况并非总是如此,尽管我之前为 MyAsyncTask1 调用了执行MyAsyncTask2.

What I need is to have MyAsyncTask1 executed before MyAsyncTask2, which is not always the case, eventhough I am calling execute for MyAsyncTask1 before MyAsyncTask2.

我实际上拥有的是自定义活动:

What I actually have is a custom activity :

public abstract class CustomActivity extends Activity {

    @Override
    protected void onCreate ( Bundle savedInstanceState ) {
        super.onCreate ( savedInstanceState );
        new MyAsyncTask2 ().execute ();
    }
}

另一个从自定义活动继承的活动:

And another activity that inherits from the custom activity :

public class MainActivity extends CustomActivity {

    @Override
    protected void onCreate ( Bundle savedInstanceState ) {
        new MyAsyncTask1 ().execute ();
        super.onCreate ( savedInstanceState );
    }
}

所以如果我使用 MainActivityMyAsyncTask1 应该在 MyAsyncTask2 之前执行,至少这是我需要的行为.

So if I use the MainActivity, MyAsyncTask1 should be executed before MyAsyncTask2, at least that is the behavior I need.

推荐答案

确保两个线程(这就是 AsyncTasks 基本上就是这样)按照你想要的顺序执行的唯一方法是在第一个线程时启动第二个线程结束.

The only way to ensure that two threads (that's what AsyncTasks basically are) are executed in the order you want, is to start the second thread when the first one finishes.

在您的情况下,为了保持实现抽象并且不必在 AsyncTask1 的 onPostExecute 中实际调用 AsyncTask2(Anup 和 Sanket 建议的方式,如果您想混合它们也可以),让 AsyncTask1 调用 super.executeAsyncTask2(),其中 executeAsyncTask2() 是 CustomActivity 中的一个方法,它启动第二个 AsyncTask

In your case, to keep implementation abstracted and not have to actually call AsyncTask2 in the onPostExecute of AsyncTask1 (the way Anup and Sanket suggested, which is also fine if you want to mix them), make AsyncTask1 call super.executeAsyncTask2(), where executeAsyncTask2() is a method in your CustomActivity which starts the second AsyncTask

这篇关于Android AsyncTask - 执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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