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/