From a OO perspective, business logic stuff should be always isolated from UI stuff. I would isolating and centralizing all my business call like getSong(), getStore() etc. into a POJO, and keep my activity class only focus on UI manipulation/rendering, this is how I do it:
- Define an interface IBusinessDAO
- Define RealBusinessDAO implements IBusinessDAO
- Define MockBusinessDAO implements IBusinessDAO
Call IBusinessDAO.getSong(); inside AsyncTask.doInBackground()
public class MyActivity extends Activity {
IBusinessDAO businessDAO;
... ...
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
... ...
protected void doInBackground(Void... params) {
businessDAO.getSong();
}
}
... ...
public void onCreate(Bundle savedInstanceState) {
if (runInTest)
businessDAO = new MockBusinessDAO();
else
businessDAO = new RealBusinessDAO();
new myAsyncTask().execute();
}
}
So in each of your AsyncTask implementation among different Activities, your AsyncTask.doInBackgroud() will be simple and clean, resulting keeping your code more efficient and maintainable.
It also help improve code testability, for unit-test your business logic, as it is a POJO, you can use purely JUnit write your test case. Sometimes we want to test UI component and we don't really care how underlying business logic is implemented, for instance, my business logic connect to remote http server download some json data, I don't want to do this every time when I just want to test the UI layout, for this situation, I can easily change all my Activities use MockBusinessDAO (sort of Spring's DI concept), to test UI component without concerning How the actual business logic is implemented.
Last, it also improve your code reusability as your businesDAO is nothing related to Andriod other than a classic POJO, in addition, you don't need concern any concurrency within your BusinessDAO implementation, as all it's methods will be called inside AsyncTask.doInBackground() method.
Hope that help.