Updating object in memory when Activity is stopped
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 t开发者_如何学Chat Activity and has clicked a "save" button.
As I understand it, you can't safely access the member variable because Android could have reclaimed it.
Nope, as long as you have a reference to an object (including Activity
instances) then it still exists. Your first Activity
still exists while it is in the stopped state... it is fine for your AsyncTask
to update UI elements or any associated data.
It is however possible for your Activity
to be permanently removed from your task while your AsyncTask
is 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 call getLastNonConfigurationInstance()
from onCreate()
to handle this. (Obviously your AsyncTask
that'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 WeakReferences
on 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.
You can just use Intents to send the result to the Activity who started the AsyncTask (you can do that in onPostExecute
method), the OS will bring it to front or will re-launch it if it is stopped.
Then in your activity onCreate
you have to make a getIntent
and check if it has the result, also you need to implement onNewIntent
callback so you are notified if your Activity is currently running an receives the Intent with the data, you have to call getIntent
also in this callback.
精彩评论