Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

android - Start AsyncTask from another AsyncTask doInBackground()

I'm trying to start an AsyncTask from another AsyncTask's doInBackground()-method...

Is this even possible? If yes, how can I achieve this?

LATER EDIT:

The idea is that I start an asynctask that will get me statuses from Tweeter ... Everything ok until here ... But when I encounter some specific tweets I need to modify them with some info from my server, here I will make another network operation, and since I need to wait until I get the info from my server I do:

GetContent getContentServiceAsyncTask = new GetContent(context);
try {
    tweetText = Uri.decode(getContentServiceAsyncTask.execute(
            URL_GET_CONTENT, jsonRequest).get());
} catch (InterruptedException e) {
    Log.e(TAG_DEBUG, "InterruptedException: ", e);
} catch (ExecutionException e) {
    Log.e(TAG_DEBUG, "ExecutionException: ", e);
}

This is started from the allready started AsyncTask in doInBackground() method ...

I know I can just add the methods in the AsyncTask and just call them in the doInBackground() method, but I need to use them in other places, where I start these AsyncTasks from onPostExecute ...

If you guys think there is an easy work-around for this, that won't affect my performance, that will be great ... if not I will make some static methods that I will call in all the AsyncTasks I need(but this will require me to modify a lot of my code)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

AsyncTasks are supposed to run from main (UI) thread. You should not run another AsyncTask from doInBackground because this method is executed on a non-UI thread.

In your case, I can suggest you two things:

  1. Combine the processing of your both AsyncTaks in a single request
  2. Launch your second AsyncTask from onPostExecute of your first task.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...