Android AsyncTask Starting Another AsyncTask

2019-06-22 12:52发布

问题:

I'm currently doing something like this in the AsyncTask's onPostExecute method, where NewTask is not the current task that's executing:

private class OlderTask extends AsyncTask<String, Void, Integer> {
    //other functions (not important)

    @Override
    protected void onPostExecute(Integer result) {
        new NewTask().execute(null, null);
    }
}

I'm wondering if this is a bad idea. Will doing so cause GC for the OlderTask to wait for the NewTask? Are there any other possible problems with using such an approach?

And if this is a problem, how can I rectify it?

回答1:

Unless NewTask is inner non static class in OlderTask it will not prevent GC from collecting OlderTask unless you store reference to it in some other way.

But even if GC will wait until NewTask is done it should not be a big deal unless you save lot of data in OlderTask or create lots of copies of OlderTask.

So if your design requires doing that, it's ok. But it surely cleaner not to have chained tasks.



回答2:

I use a callback method, So when result comes to onPostExecute I call another AsynkTask from UI, I think it is good idea, Let me know what do you think.

public class PatientSearchController extends AsyncTask < String, Void, String > {

    private PatientSearchResultHandler handler = null;

    public void onResultHandler(PatientSearchResultHandler handler) {
        this.handler = handler;
    }

    @Override
    protected String doInBackground(String...params) {

    }

    @Override
    protected void onPostExecute(String result) {
        this.handler.onResultSuccessHandler(result);
    }
}