Android AsyncTask - Order of execution

前端 未结 6 1246
醉酒成梦
醉酒成梦 2020-12-30 07:58

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

My question is :

Assuming I have 2 implementations of AsyncTask : MyAsyncTask1

6条回答
  •  孤独总比滥情好
    2020-12-30 08:41

    In order to "chain" any number of AsyncTasks, what I do is have my AsyncTasks recieve a custom Callback as a parameter. You just have to define it like this:

    public interface AsyncCallback(){
        public void onAsyncTaskFinished();
    }
    

    Your AsyncTask implementation constructor should have an AsyncCallback as a parameter, like this:

    private AsyncCallback callback;
    
    public AsyncTaskImplementation(AsyncCallback callback){
        //Do whatever you're doing here
        this.callback = callback;
    }
    

    Of course if they have more parameters, don't delete them.

    Then, just before the end of onPostExecute, introduce this:

    if (callback != null) callback.onAsyncTaskFinished();
    

    So, if you pass a callback, the AsyncTask will execute your callback in the main thread. If you don't want to execute any callback, just pass null

    So, to call your AsyncTask chain you just write this:

    new AsyncTask1(new AsyncCallback(){
    
        public void onAsyncTaskFinished(){
             new AsyncTask2(null).execute();
        }
    
    }).execute();
    

    I hope this helps you ;-)

提交回复
热议问题