3

Basically, I have one Asynctask for downloading files. I can call this from my main UI activity fine, but what if I want to call it from a different Activity - I.e. one activity is a main menu with a link to download the manual, and another activity is a ListView of all the available documents to be downloaded.

Do I have to create another Asynctask for this?

DreamsOfHummus
  • 735
  • 2
  • 7
  • 18

2 Answers2

6

I am guessing you have AsyncTask in your MainActivity as an innerclass. You can take the code of AsyncTask and put it in a new file which is public(or accessable) to both classes. Remember that you cann't execute an instance of an AsyncTask more than once, but you can create multiple instances of the AsyncTask.

class MainActivity{
new MyTask().execute();
}

.

class DifferentActivity {
  new MyTask().execute();//a new instance
}

.

class MyTask extends AsyncTask{
   public MyTask(Context context){
   }//Pass in context.
}

All different files.

Community
  • 1
  • 1
wtsang02
  • 18,603
  • 10
  • 49
  • 67
0

Asynctasks must be called from the UI thread which usually would be the running activity.

It sounds like these activities are started through intents and they display their own UI's so yes you can run Asynctasks from them.

The only stipulation is now you need to declare/define the asynctask in a place all the activities can see (so maybe make a class that extends async task com.myapp.MyAsyncTask that also includes the activities e.g. com.myapp.MyMainMenuActivity).

paulczak
  • 96
  • 6