Android Services

Android Services

In this talk we show the different types of Services that exist in Android and how we can use them in our applications to perform operations in the background. GDG DevFest Sur 2013. #DevFestSur

The sample codes used in this talk can be found at GitHub: https://github.com/josejuansanchez/GDG-DevFestSur-2013

Transcript

  1. Android  Services   José  Juan  Sánchez  Hernández   @josejuansanchez  

  2. Ac7vi7es   Ac7vi7es   Ac7vi7es   Ac7vi7es   Ac7vi7es  

    Services   Ac7vi7es   Ac7vi7es   Receivers   Ac7vi7es   Ac7vi7es   Providers   Dalvik  VM   Libs   DB   Files   res   Android  Applica7on  Anatomy   Process   Applica7on  /  APK  Package   Applica7on  =  Set  of  Android  Components     •  It  contains  any  number  of  Ac#vi#es,   Services,  Receivers  and  Providers.     •  It  has  its  own  file  system,  database,   place  to  store  na7ve  libraries.     •  No  other  app  can  access  any  of  its   data  without  prior  permission.   2/36  
  3. Process   Applica7on  /  APK  Package   Run7me  Overview  

    Image:  Marko  Gargenta   Android  Internals  Overview   3/36  
  4. Process   Applica7on  /  APK  Package   Zygote   4/36

     
  5. Process   Applica7on  /  APK  Package   Process  Basics  

    •  Android  Process  ==  Linux  Process.   •  By  default,  1  Process  per  APK.   •  By  default,  1  Thread  per  Process.     Threads  on  Android   •  By  default,  each  process  has  1  thread.   •  Mosts  components  share  the  single  thread.   Threads  and  Loopers   •  Each  thread  has  a  Looper  to  handle  a  message  queue.   •  Events  from  all  components  are  interleaved  into  Looper.                E.g.  View  UI  events,  IntentReceivers  firing,  etc.   •  Loopers  cannot  accommodate  mul7-­‐threaded  access.              They  are  designed  to  play  nicely  with  MessageHandlers.   Processes  and  Threads   5/36  
  6. Ac7vity   Service   Main  Thread        

            Looper   Message   Queue   System   Events   UI   Events   Process   Applica7on  /  APK  Package   Processes  and  Threads   6/36  
  7. Services   7/36   What  is  a  Service?   • 

    Is  a  component  that  can  perform  long-­‐running  opera7ons  in  the  background.   •  They  can  be  started  and  stopped.   •  Services  doesn't  have  UI  and  does  not  provide  direct  access  to  the  UI.     What  a  Service  is  NOT?   •  A  Service  is  not  a  separate  process.   •  A  Service  is  not  a  thread.   Examples   •  Playing  music  even  if  the  player  ac7vity  gets  garbage-­‐collected.   •  Polling  the  Internet  for  RSS/Atom  feed  updates.   •  Performing  periodic  work  without  user  interven7on  (scheduled  tasks).   •  An  applica7on  that  con7nually  logs  the  geographical  coordinates  of  the  device.    
  8. Process   Applica7on  /  APK  Package   Started   A

     service  is  “started”  when  an   applica7on  component  starts  it  by   calling  startService().  Oien   performs  a  single  opera7on  &  might   not  return  a  result  to  the  caller   directly.     Bound   A  service  is  “bound”  when  an   applica7on  component  binds  to  it  by   calling  bindService().  Provides  a   client-­‐  server  interface  that  allows  for   a  conversa7on  with  the  Service.   Types  of  Services   Android  Developers.  API  Guides   hkps://developer.android.com/guide/components/services.html   8/36  
  9. Applica7on  /  APK  Package   Started  Services   There  are

     two  classes  you  can  extend  to  create  a  started  service:   Service  and  IntentService     9/36  
  10. Ac7vity   Service   Main  Thread        

            Looper   Message   Queue   System   Events   UI   Events   Process   Applica7on  /  APK  Package   Example:  LocalService  /  1  Process   10/36   Bad  Prac7ce!  May  block  the  Main  Thread  L  
  11. Example:  LocalService  /  1  Process   11/36  

  12. Example:  LocalService  /  1  Process   12/36  

  13. The  service  should  remain  stopped  un7l     explicitly  started

     by  applica7on  code   13/36  
  14. Example:  LocalService  /  1  Process   14/36   START_NOT_STICKY If

     the  system  kills  the  service,  do  not  recreate  the  service,  unless  there  are  pending  intents   to  deliver.  This  is  the  safest  op7on  to  avoid  running  your  service  when  not  necessary  and   when  your  applica7on  can  simply  restart  any  unfinished  jobs.     START_STICKY If  the  system  kills  the  service,  recreate  the  service  and  call  onStartCommand(),  but  do   not  redeliver  the  last  intent.  Instead,  the  system  calls  onStartCommand()  with  a  null   intent,  unless  there  were  pending  intents  to  start  the  service,  in  which  case,  those  intents   are  delivered.  This  is  suitable  for  media  players  (or  similar  services)  that  are  not  execu7ng   commands,  but  running  indefinitely  and  wai7ng  for  a  job.     START_REDELIVER_INTENT If  the  system  kills  the  service,  recreate  the  service  and  call  onStartCommand()  with  the   last  intent  that  was  delivered  to  the  service.  Any  pending  intents  are  delivered  in  turn.  This   is  suitable  for  services  that  are  ac7vely  performing  a  job  that  should  be  immediately   resumed,  such  as  downloading  a  file.  
  15. Don’t  forget  it!!   15/36  

  16. Good  Prac7ce!  J   16/36   Leaving  a  service  running

     when  it’s  not  needed  is     one  of  the  worst  memory-­‐management  mistakes     an  Android  app  can  make.       So  don’t  be  greedy  by  keeping  a  service  for  your  app  running.     Not  only  will  it  increase  the  risk  of  your  app  performing  poorly  due  to  RAM   constraints,  but  users  will  discover  such  misbehaving  apps  and  uninstall  them.       Managing  Your  App's  Memory   hkp://developer.android.com/training/ar7cles/memory.html   Use  services  sparingly  
  17. Example:  LocalService  /  1  Process   17/36  

  18. 18/36  

  19. Ac7vity   Main   Thread          

          Looper   Message   Queue   Syst.   Events   UI   Events   Service   Main   Thread                 Looper   Message   Queue   Syst.   Events   Process   Process   Applica7on  /  APK  Package   Example:  RemoteService  /  2  Processes   19/36   “Remote”  in  this  example  means  that  the  Service  is  hosted  in  another  process.  
  20. Example:  RemoteService  /  2  Processes   20/36  

  21. Example:  RemoteService  /  2  Processes   21/36  

  22. Applica7on  /  APK  Package   22/36   Use  mul7ple  processes

      An  advanced  technique  that  may  help  you  manage  your  app's  memory  is   dividing  components  of  your  app  into  mul7ple  processes.       An  example  of  when  mul7ple  processes  may  be  appropriate  is  when  building   a  music  player  that  plays  music  from  a  service  for  long  period  of  7me.   Managing  Your  App's  Memory   hkp://developer.android.com/training/ar7cles/memory.html   Good  Prac7ce!  J  
  23. Ac7vity   Main   Thread          

          Looper   Message   Queue   Syst.   Events   UI   Events   Service   Handler   Thread                 Looper   Message   Queue   Process   Applica7on  /  APK  Package   Example:  Service  +  HandlerThread  /  1  Process   23/36   HandlerThread  inherits  from  Thread  and  encapsulates  a  Looper-­‐object.   Is  a  Thread  with  a  message  queue  and  processing  loop.  
  24. Don’t  forget  it!!   24/36   Example:  Service  +  HandlerThread

     /  1  Process  
  25. 25/36   Example:  Service  +  HandlerThread  /  1  Process  

  26. Example:  Service  +  HandlerThread  /  1  Process   26/36  

  27. 27/36  

  28. Ac7vity   Main   Thread          

          Looper   Message   Queue   Syst.   Events   UI   Events   IntentService   Worker   Thread                 Looper   Message   Queue   Process   Applica7on  /  APK  Package   Example:  IntentService  /  1  Process   36/36   This  is  the  best  op#on  if  you  don't  require  that  your  service   handle  mul7ple  requests  simultaneously  
  29. Example.  IntentService  /  1  Process   29/36   You  never

     have  to  call  stopSelf().     Stops  itself  when  it  runs  out  of  work.  
  30. Example.  IntentService  /  1  Process   30/36  

  31. 1)  When  to  use?   •  The  Service  can  be

     used  in  tasks  with  no  UI,  but  shouldn't  be  too  long.  If  you  need  to   perform  long  tasks,  you  must  use  threads  within  Service  or  use  another  process.   •  The  IntentService  can  be  used  in  long  tasks  usually  with  no  communica7on  to  Main   Thread.  This  is  the  best  op7on  if  you  don't  require  that  your  service  handle  mul7ple   requests  simultaneously.   2)  Triggered  From   •  The  Service  may  be  triggered  from  any  thread.   •  The  IntentService  must  be  triggered  from  Main  Thread.     3)  Runs  On   •  The  Service  runs  in  background  but  it  runs  on  the  Main  Thread  of  the  applica7on.   •  The  IntentService  runs  on  a  separate  Worker  Thread.     4)  Limita#ons  /  Drawbacks   •  The  Service  may  block  the  Main  Thread  of  the  applica7on.   •  The  IntentService  cannot  run  tasks  in  parallel.     Service  vs  IntentService   31/36  
  32. There  are  several  ways  to  get  results  from  a  Service

     back  to  an  invoking  Ac7vity:   •  Broadcast  Intents              This  requires  having  the  Ac7vity  register  a  BroadcastReceiver.   •  Messenger  object              This  object  can  send  messages  to  an  Ac7vity’s  Handler.   •  Pending  Intent              Using  a  Pending  Intent  to  trigger  a  call  to  Ac7vity’s  onActivityResult()!     Another  approach  is  to  let  the  user  know  directly  about  the  work  that  was   completed.  To  do  that,  a  Service  can  raise  a  No#fica#on.   Communica7ng  from  Services   32/36  
  33. Process   Applica7on  /  APK  Package   33/36   Bound

     Services  
  34. Ac7vity             Main   Thread

                    Looper   Message   Queue   RemoteService   Process   Process   Applica7on  A  /  APK  Package   Example:  Remote  Bound  Services   34/36   RemoteBinder         getRandomNumber()   Applica7on  B  /  APK  Package   mBound   1.  Call  method   2.  Return  results   to  caller   Binder  IPC   Mechanism   We  need  interprocess  communica7on  (IPC)  
  35. Ac7vity             Main   Thread

                    Looper   Message   Queue   RemoteService   Process   Applica7on  A  /  APK  Package   Example:  Locally  Bound  Services   35/36   RemoteBinder         getRandomNumber()   mBound   1.  Call  method   2.  Return  results   to  caller    Because  the  service  runs  in  the  same  process  as  its  clients,     we  don't  need  to  deal  with  IPC  
  36. José  Juan  Sánchez  Hernández   @josejuansanchez