Android AsyncTask - 执行顺序

Lee*_*elo 11 android android-asynctask

我正面临着关于AsyncTasks执行顺序的问题.

我的问题是:

假设我有2个AsyncTask实现:MyAsyncTask1MyAsyncTask2

以下列方式调用:

new MyAsyncTask1 ().execute ();
new MyAsyncTask2 ().execute ();
Run Code Online (Sandbox Code Playgroud)

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

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

我需要的是有MyAsyncTask1之前执行MyAsyncTask2,这是情况并非总是如此沉绵我呼吁执行对MyAsyncTask1之前MyAsyncTask2.

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

public abstract class CustomActivity extends Activity {

    @Override
    protected void onCreate ( Bundle savedInstanceState ) {
        super.onCreate ( savedInstanceState );
        new MyAsyncTask2 ().execute ();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

public class MainActivity extends CustomActivity {

    @Override
    protected void onCreate ( Bundle savedInstanceState ) {
        new MyAsyncTask1 ().execute ();
        super.onCreate ( savedInstanceState );
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,如果我使用MainActivity,MyAsyncTask1应该在MyAsyncTask2之前执行,至少这是我需要的行为.

zrg*_*giu 5

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.

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