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
There's no single "correct" way of implementing AsyncTask
. But here are my two cents:
This class is intended to perform "light" work in the context of an Activity. That's why it has the methods onPreExecute
, onProgressUpdate
, onPostExecute
running in the UI thread, so that they can access fields and update GUI quickly. Any task that might take a longer time to complete and it is not meant to update a specific activity should be moved to a Service.
Those methods are mostly used to update the GUI. As the GUI is something related to the Activity instance (the fields are likely declared as private member variables), it is more convenient to implement the AsyncTask
as a non-static nested class. It is also the most natural way in my opinion.
In case the task is going to be reused in other activities, I think it should be allowed to have its own class. To be honest, I'm no fan of static nested classes, especially inside views. If it is a class it means it is conceptually different than the activity. And if it is static it means it is not related to this concrete instance of the activity. But as they are nested, those classes are visually inside the parent class making it harder to read, and can go unnoticed in the project package explorer as it only shows files. And despite being less coupled than inner classes, this is not really that useful: if the class changes, you have to merge/commit the whole parent file to the version control. If you where to reuse it, then you'll have to access it as Parent.Nested
everywhere. So in order to not to couple other activities to the Parent
class, you probably would like to refactor it and extract the nested class to its own file.
So for me the question would be Inner Class vs Top-Level Class.