-2

I want to use same AsyncTask in more than 2 activities. It is not practical solution to write same code in every activity. My question is,

How can I create class with AsyncTask GLOBALLY and use it any where?

My second IMPORTANT question is:

How can I get return value from onPostExecution() to every activity?

Parth Pandya
  • 63
  • 1
  • 5

2 Answers2

0

To run the asynctask from anywhere you could use otto:

If you are using android studio you add it the dependency or eclipse you download it as a jar : refer to this link : http://square.github.io/otto/

First you declare the singltone:

public class MyBus {

private static final Bus BUS = new Bus();

public static Bus getInstance() {
return BUS;
 }
}

Then you create a separate asynctask class :

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

@Override protected String doInBackground(Void... params) {
Random random = new Random();
final long sleep = random.nextInt(10);
try {
  Thread.sleep(sleep * 1000);
} catch (InterruptedException e) {
  e.printStackTrace();
}
return "Slept for " + sleep + " seconds";
}

@Override protected void onPostExecute(String result) {
MyBus.getInstance().post(new AsyncTaskResultEvent(result));
 }
}

Then from inside the activity : you register the Bus and call new MyAsyncTask().execute();

Do not forget to unregister the bus on destroy:

Refer to this tutorial for more help: http://simonvt.net/2014/04/17/asynctask-is-bad-and-you-should-feel-bad/

Miriana Itani
  • 865
  • 9
  • 25
0
public class MyAsyncTask extends AsyncTask<Void, Void, String> {
    private OnResultReceived mListner;
    public MyAsyncTask(OnResultReceived listner){
        this.mListner=listner;  
    }       
    @Override protected String doInBackground(Void... params) {
            //DO YOUR STUFF
        String data="Test";     
        return data;
        }

    @Override protected void onPostExecute(String result) {
        if(mListner!=null)mListner.onResult(result);
    }

public interface OnResultReceived{
    public void onResult(String result);
}       
}

in Activity

new MyAsyncTask(new OnResultReceived{
    public void onResult(String data){
        //Your Result from AsyncTask    
    }
}).execute();
NullByte
  • 165
  • 1
  • 6