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

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

问题描述

我现在面临一个问题,关于AsyncTasks的exection的顺序。

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

我的问题是:

假设我有AsyncTask的2个实现: MyAsyncTask1 MyAsyncTask2

Assuming I have 2 implementations of AsyncTask : MyAsyncTask1 and MyAsyncTask2

这被称为以下列方式:

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

难道是保证下的 MyAsyncTask1 之前执行 MyAsyncTask2 ? 有一点可以肯定,他们不是在并行执行,因为默认执行程序使用,这是 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 ??

我需要的是有 MyAsyncTask1 之前执行 MyAsyncTask2 ,这是情况并非总是如此,eventhough我呼吁执行 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 );
    }
}

所以,如果我使用 MainActivity MyAsyncTask1 之前应执行 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.

在你的情况下,要保持执行抽象,而不必实际调用AsyncTask2在 onPostExecute AsyncTask1(顺便阿努普和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

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

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