Rarw
Rarw

Reputation: 7663

Use one instance of AsyncTask throughout Activity

I have a number of AsyncTask set up as individual classes. I reuse them throughout my app. I wonder, in places where the same AsyncTask may be needed more than one is it possible to use one instance of that custom AsyncTask class multiple times? This is really a cosmetic problem since it bothers me having redundant sections of code, especially when an AsyncTask uses a callback to communicate with it's starting activity.

I've tried to do it this way -

MyTask task = new MyTask(new someCallBackListener){

    @Override
    public void taskDone(boolean youDone){

    }
});

And then in my activity just calling

task.execute(params);

This seems to work the first time, but I cannot execute it more than once. Do I really just need to initialize a new task each time I want to use it?

Upvotes: 0

Views: 800

Answers (2)

Jofre Mateu
Jofre Mateu

Reputation: 2430

While you can't use twice the same instance I think you could reuse the callback implementation by creating the instance this way

new MyTask(this).execute(params);

and implementing the callback in the Activity or the Fragment like this

public class SomeActivity extends Activity implements MyTask.someCallBackListener {

    //All the Activity code

    public void taskDone(boolean youDone) {

    }
}

This way, you can create multiple instances of your AsyncTask without those redundant sections of code that bother you.

Upvotes: 1

rahulserver
rahulserver

Reputation: 11205

An asynctask can be executed only once as per the android documentation here(section Threading rules)which says

The task can be executed only once (an exception will be thrown if a second execution is attempted.)

So its not possible to reuse an AsyncTask instance. Further this SO link would help you!

Upvotes: 2

Related Questions