English subtitles

← Using Alarms - Developing Android Apps

Get Embed Code
7 Languages

Showing Revision 10 created 05/24/2016 by Udacity Robot.

  1. So now we have a simple service.
  2. Wasn't that easy?
  3. But it still doesn't wake itself up.
  4. Fortunately, there's
    a system service for that.
  5. This is a good opportunity to
    introduce the alarm manager.
  6. The alarm manager allows you to
    tell the system that you want it to
  7. wake a component of your application
    up after a period of time and
  8. do some processing in the background.
  9. You can even have it wake up your
    application periodically, but
  10. what do we wake up in the background?
  11. That would be an Android
    component we haven't seen before,
  12. called a broadcast receiver.
  13. A broadcast receiver is a special
    class that is used to receive
  14. intent broadcasts,
    often from other applications.
  15. Typically, a broadcast receiver
    will register an intent filter for
  16. these broadcasts.
  17. It's also one way the application
    will listen in on alarms.
  18. Alarms take advantage of a new kind
    of intent, called a PendingIntent.
  19. A PendingIntent is
    a special kind of intent
  20. that is handed from one
    application to another.
  21. The big difference between
    a PendingIntent and a regular intent
  22. is that a PendingIntent gives permission
    for the app using it to send data with
  23. the same permissions and application
    identity as the app that created it.
  24. In Android this allows the system
    process to call your application back
  25. in a specific asynchronous way without
    compromising the Android security model.
  26. In alarms a pending intent
    is used by the alarm manager
  27. to talk to the broadcast
    receiver we create.
  28. Let's add some alarm stuff.
  29. First, I'm going to add
    a BroadcastReceiver as a static inner
  30. class of SunshineService.
  31. Since this is an Android component,
  32. I'll register this broadcast
    receiver in the manifest.
  33. Note the way a static
    inner class is notated.
  34. Okay.
  35. I've given you the bones of a broadcast
    receiver that can handle an alarm.
  36. But now it's your turn.
  37. You can create a PendingIntent
    from an explicit intent
  38. to have the alarm manager
    activate your broadcast receiver.
  39. I recommend setting the alarm
    to something absurdly short,
  40. like five seconds, so
    you can easily test that it's working.