Reputation: 1469
I'm wondering where I should place my AsyncTask
in my android project. As of right now I'm implementing an AsyncTask
as a private class of my activity its running under. What I am going to do is in each activity that has a network call I will implement its own private class of AsyncTask
. I have a few questions though
In The
preexecute
method it says I can interact with the activity and place a spinner or progress bar. I do this by usingMy_Activity_Class_Name.this
. So my question is does that line of code reference the activity theAsyncTask
is called from? If so I believe that will be a static method. How do i actually pass in the instance of the class so I can interact with non static functions?I want to place all my Async code into one class for its respective needs. My quesiotn though is if i need to return a type back to the class that calls the Async method how can I return a value? Also is this the best practice?
Upvotes: 1
Views: 117
Reputation: 49986
You should make your inner private AsyncTask class - static. This is because otherwise it will have implicit reference to your Activity - this means that if your Activity will be recreated - ie. due to config change - then your AsyncTask will still hold your activity reference causing reference leak. This means you should pass reference to your activity to AsyncTask in ie. constructor of AsyncTask, and keep it in WeakReference (WeakReference/AsyncTask pattern in android).
So my question is does that line of code reference the activity the ASYNC Task is called from?
yes, but only if your AsyncTask class is non static
If so I beleve that will be a static method. How do i actually pass in the instance of the class so i can interact with non static functions?
its not a static method, with My_Activity_Class_Name.this you can access non static methods of your Activity class.
My quesiotn though is if i need to return a type back to the class that calls the Async method how can I return a value? Also is this the best practice?
You can call a method on your Activity class, there is nothing wrong with that. Remember that you cannot access UI widgets from non UI thread. So update your Activity widgets from onPostExecute which is called on UI thread.
Upvotes: 1