Reputation: 109
In regards to Async Task in android it is best practice to include them as a Inner Class of the Activity you are working in or is it better to have the as their own stand alone class? for example
public MyClass extents Activity
{
public void onCreate(){
}
public class MyAsyncTask extents AsyncTask<Void, Void, Void>
{
protected void doInBackground()
{
//do stuff here....
}
}
public void onResume(){
}
}
or as an external class
public class MyAsyncTask extents AsyncTask<Void, Void, Void>
{
protected void doInBackground()
{
//do stuff here....
}
}
public MyClass extents Activity
{
public void onCreate(){
}
}
Upvotes: 3
Views: 1916
Reputation: 4573
AsyncTask
has it's own lifecycle which doesn't depend on Activity
lifecycle. You need to make sure that it doesn't have a reference to activity or views when activity is already destroyed.
Implementing AsyncTask
as an inner class makes sense only if it's static
. If it's not static then it will have an implicit reference to outer activity which will lead to memory leaks. If you need references to views from your static async task use WeakReference
.
Implementing AsyncTask
in a separate file is also a good idea, but same rules applied. Use weak references if needed.
The only difference between static
inner async task and async task in a separate file is code readability. If there is a lot of logic inside async task, go ahead with a separate file.
Upvotes: 9