Best way to manage the ProgressDialog from AsyncTask

后端 未结 2 1783
太阳男子
太阳男子 2020-11-28 12:37

I would like to use the AsyncTask for manage some business logic in my application. What is the best pattern for using the onProgressUpdate(...) me

相关标签:
2条回答
  • 2020-11-28 12:56

    I would rather isolate business logic stuff from AsyncTask than isolate AsyncTask from Activity.

    In general, AsyncTask has a very specific design and use case in Android application life cycle, that is, run some time consuming task in the background thread, once done, update Activity's view in UI thread. This is why it is always recommended to use it as a inner class of Activity.

    A more OO design IMO is isolating and centralizing your business logic into a POJO (for reusability). For testability, you can do something like this:
    1. Define an interface IBusinessDAO
    2. Define RealBusinessDAO implements IBusinessDAO
    3. Define MockBusinessDAO implements IBusinessDAO
    4. Call IBusinessDAO.foo(); inside AsyncTask.doInBackground()

    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 my Activity use MockBusinessDAO (sort of Spring's DI concept) like this:

    public class MyActivity extends Activity {
      IBusinessDAO businessDAO;
    
      ... ...
    
      private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
        ... ...        
    
        protected void doInBackground(Void... params) {
          businessDAO.foo();
        }
      }
    
      ... ...
    
      public void onCreate(Bundle savedInstanceState) {
        if (runInTest)
          businessDAO = new MockBusinessDAO();
        else
          businessDAO = new RealBusinessDAO();
    
        new myAsyncTask().execute();
      }
    
    
    }
    

    Some advantages of doing these are:
    1. AsyncTask implementation is easy and clean (several lines of code in doInBacnground())
    2. Business logic implementation is purely POJO, improve reusability.
    3. Isolation test business logic and UI component, improve testability.

    Hope that help.

    0 讨论(0)
  • 2020-11-28 13:03
    1. Solution number one is probably how I would handle it - That is the way of the Android framework. A twist to this solution (and probably how I would handle it, if the AsyncTask couldn't fit into the Activity-class) I would pass a Context as the parameter instead, and then instantiate and show the ProgressDialog in onPreExecute.

    2. Solution number 2 is basicly the same as creating the dialog as an inner class - so you might aswell do that if you go for this one.

    0 讨论(0)
提交回复
热议问题