Return to Video

Sunshine in the Background - Developing Android Apps

  • 0:00 - 0:04
    Remember back in lesson two
    when Katherine used
  • 0:04 - 0:07
    an AsyncTask hooked up to
    a refresh button to update our data?
  • 0:07 - 0:10
    Rato talked about how
    that was a bad idea
  • 0:10 - 0:15
    because the AsyncTask is not tied
    to the activity life cycle.
  • 0:15 - 0:18
    The virtual machine will hold on
    to the activity object
  • 0:18 - 0:21
    as long as the AsyncTask is running,
    even after Android
  • 0:21 - 0:26
    has called onDestroy for the activity
    and expect it to be discarded.
  • 0:26 - 0:28
    If you rotate your phone,
    the behavior is to destroy
  • 0:28 - 0:32
    your activity and instantiate a new one.
  • 0:32 - 0:35
    The naive AsyncTask implementation
    now has two threads
  • 0:35 - 0:39
    trying to perform the same update,
    and so forth.
  • 0:39 - 0:41
    The point is, it's not
    the best pattern
  • 0:41 - 0:44
    for a potentially
    very long background operation,
  • 0:44 - 0:46
    such as fetching from web services.
  • 0:46 - 0:48
    If you leave the app,
    the AsyncTask will continue to run
  • 0:48 - 0:51
    for as long as your process is kept alive,
  • 0:51 - 0:54
    but will run at a low priority,
    and your process
  • 0:54 - 0:56
    will be the first thing
    to be killed if the device
  • 0:56 - 0:58
    needs more resources.
  • 0:58 - 1:00
    And there's a bigger problem.
  • 1:00 - 1:02
    Your app has to be visible
    and running in the foreground
  • 1:02 - 1:05
    to instantiate the task
    in the first place.
  • 1:05 - 1:06
    Because we started a task,
  • 1:06 - 1:09
    to update the weather
    when we started the app,
  • 1:09 - 1:13
    this can have undesirable behavior
    if the weather changes rapidly.
  • 1:13 - 1:16
    So now we're going to learn
    the right way to perform updates.
  • 1:16 - 1:19
    We'll want to automate
    the process while the app
  • 1:19 - 1:20
    is in the foreground.
  • 1:20 - 1:23
    But even more importantly,
    we want the app to get
  • 1:23 - 1:26
    regular updates in the background
    with minimal battery drain.
  • 1:26 - 1:29
    That will be especially important
    later in this lesson
  • 1:29 - 1:31
    when we introduce
    weather notifications.
Title:
Sunshine in the Background - Developing Android Apps
Description:

more » « less
Video Language:
English
Team:
Udacity
Project:
UD853 - Developing Android Apps
Duration:
01:32

English subtitles

Revisions Compare revisions