-
Remember back in lesson two
when Katherine used
-
an AsyncTask hooked up to
a refresh button to update our data?
-
Rato talked about how
that was a bad idea
-
because the AsyncTask is not tied
to the activity life cycle.
-
The virtual machine will hold on
to the activity object
-
as long as the AsyncTask is running,
even after Android
-
has called onDestroy for the activity
and expect it to be discarded.
-
If you rotate your phone,
the behavior is to destroy
-
your activity and instantiate a new one.
-
The naive AsyncTask implementation
now has two threads
-
trying to perform the same update,
and so forth.
-
The point is, it's not
the best pattern
-
for a potentially
very long background operation,
-
such as fetching from web services.
-
If you leave the app,
the AsyncTask will continue to run
-
for as long as your process is kept alive,
-
but will run at a low priority,
and your process
-
will be the first thing
to be killed if the device
-
needs more resources.
-
And there's a bigger problem.
-
Your app has to be visible
and running in the foreground
-
to instantiate the task
in the first place.
-
Because we started a task,
-
to update the weather
when we started the app,
-
this can have undesirable behavior
if the weather changes rapidly.
-
So now we're going to learn
the right way to perform updates.
-
We'll want to automate
the process while the app
-
is in the foreground.
-
But even more importantly,
we want the app to get
-
regular updates in the background
with minimal battery drain.
-
That will be especially important
later in this lesson
-
when we introduce
weather notifications.