What's the correct way to implement AsyncTask? static or non static nested class?

前端 未结 4 924
悲&欢浪女
悲&欢浪女 2020-12-05 07:10

The \"Login\" from Android examples implemented AsyncTask as a non-static inner class. However, according to Commonsguys, this class should be static and use we

4条回答
  •  感动是毒
    2020-12-05 07:23

    The linked article already says it

    This does emphasize, though, that you want doInBackground() of your AsyncTask to be completely decoupled from the Activity. If you only touch your Activity on the main application thread, your AsyncTask can survive the orientation change intact.

    Don't touch the Activity (e.g. its members) from the AsyncTask, which is in line with Static Nested Classes

    Static Nested Classes
    As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.

    Although, the examples from Android, AsyncTask reference and Using AsyncTask are still using non-static nested classes.

    And according to this Static nested class in Java, why?, I would first go with the static inner class and resort to the non-static version only, if it is really necessary.

提交回复
热议问题