Just curious how people are handling this situation:
Let’s say when your Activity is created you launch an AsyncTask or Thread to hit a web service and retrieve a piece of data. Suppose, before the AsyncTask finishes, the user has hit some button that sends them to a new Activity. While on the new Activity, the AsyncTask finishes.
When the AsyncTask finishes, you want a member variable of the first Activity to update, but that Activity is now stopped.
What do you do? As I understand it, you can’t safely access the member variable because Android could have reclaimed it. You could use a BroadcastReceiver, but if you’re no longer on that Activity, the BR won’t receive the message. So what is the right answer?
Update:
A possibility is to have the task write to a database and read from that database in the Activity’s onResume(). However, in my case, this is not appropriate. The data in my Activity is not to be written (read: saved) to the database until the user is finished with that Activity and has clicked a “save” button.
Nope, as long as you have a reference to an object (including
Activityinstances) then it still exists. Your firstActivitystill exists while it is in the stopped state… it is fine for yourAsyncTaskto update UI elements or any associated data.It is however possible for your
Activityto be permanently removed from your task while yourAsyncTaskis running… perhaps this is what you were thinking of?The most common case is when the user simply changes the orientation of the phone. Your activity will likely be destroyed and recreated anew. If you have data which needs to survive this – it’s likely that you do – then implement
onRetainNonConfigurationInstance()and callgetLastNonConfigurationInstance()fromonCreate()to handle this. (Obviously yourAsyncTaskthat’s running through all of this should know to update things on the later instance, not the previous one).Finally, if your AsyncTask does update UI (as seems likely) then it’s better for it to keep
WeakReferenceson UI objects rather than direct references. Activities are expensive objects, and as long as something’s keeping a reference to one (and every View contains a reference to it’s owning Context/Activity), it can’t be GC’d. Very easy to leak memory that way.