Viernes Androides. Android Services

Viernes Androides. Android Services

Presentación utilizada en la V sesión de los Viernes Androides. Actividad organizada por la asociación universitaria UNIA de la Universidad de Almería. 22 de Noviembre de 2013.

http://unia.ual.es

En esta charla veremos los diferentes tipos de Services que existen en Android y cómo podemos utilizarlos en nuestras aplicaciones para realizar operaciones en background.

2e5aefd649aca2d15a7dd3c2bb0726d4?s=128

José Juan Sánchez Hernández

November 22, 2013
Tweet

Transcript

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

      @josejuansanchez   Viernes  Androides  
  2. Ac8vi8es   Ac8vi8es   Ac8vi8es   Ac8vi8es   Ac8vi8es  

    Services   Ac8vi8es   Ac8vi8es   Receivers   Ac8vi8es   Ac8vi8es   Providers   Dalvik  VM   Libs   DB   Files   res   Android  Applica8on  Anatomy   Process   Applica8on  /  APK  Package   Applica8on  =  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  na8ve  libraries.     •  No  other  app  can  access  any  of  its   data  without  prior  permission.   2/41  
  3. Process   Applica8on  /  APK  Package   Run8me  Overview  with

     Dalvik  VM   Image:  Marko  Gargenta   Android  Internals  Overview   3/41  
  4. Process   Applica8on  /  APK  Package   Zygote   4/41

     
  5. Process   Applica8on  /  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  mul8-­‐threaded  access.              They  are  designed  to  play  nicely  with  MessageHandlers.   Processes  and  Threads   5/41  
  6. Ac8vity   Service   Main  Thread        

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

    Is  a  component  that  can  perform  long-­‐running  opera8ons  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  ac8vity  gets  garbage-­‐collected.   •  Polling  the  Internet  for  RSS/Atom  feed  updates.   •  Performing  periodic  work  without  user  interven8on  (scheduled  tasks).   •  An  applica8on  that  con8nually  logs  the  geographical  coordinates  of  the  device.    
  8. Process   Applica8on  /  APK  Package   Started   A

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

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

            Looper   Message   Queue   System   Events   UI   Events   Process   Applica8on  /  APK  Package   Example:  LocalService  /  1  Process   10/41   Bad  Prac8ce!  May  block  the  Main  Thread  L   hkps://github.com/josejuansanchez/GDG-­‐DevFestSur-­‐2013/tree/master/LocalService  
  11. Example:  LocalService  /  1  Process   11/41  

  12. Example:  LocalService  /  1  Process   12/41  

  13. The  service  should  remain  stopped  un8l     explicitly  started

     by  applica8on  code   13/41  
  14. Example:  LocalService  /  1  Process   14/41   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  op8on  to  avoid  running  your  service  when  not  necessary  and   when  your  applica8on  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  execu8ng   commands,  but  running  indefinitely  and  wai8ng  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  ac8vely  performing  a  job  that  should  be  immediately   resumed,  such  as  downloading  a  file.  
  15. Don’t  forget  it!!   15/41  

  16. Good  Prac8ce!  J   16/41   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/ar8cles/memory.html   Use  services  sparingly  
  17. Example:  LocalService  /  1  Process   17/41  

  18. 18/41  

  19. Ac8vity   Main   Thread          

          Looper   Message   Queue   Syst.   Events   UI   Events   Service   Main   Thread                 Looper   Message   Queue   Syst.   Events   Process   Process   Applica8on  /  APK  Package   Example:  RemoteService  /  2  Processes   19/41   “Remote”  in  this  example  means  that  the  Service  is  hosted  in  another  process.   hkps://github.com/josejuansanchez/GDG-­‐DevFestSur-­‐2013/tree/master/RemoteService    
  20. Example:  RemoteService  /  2  Processes   20/41  

  21. Example:  RemoteService  /  2  Processes   21/41  

  22. Applica8on  /  APK  Package   22/41   Use  mul8ple  processes

      An  advanced  technique  that  may  help  you  manage  your  app's  memory  is   dividing  components  of  your  app  into  mul8ple  processes.       An  example  of  when  mul8ple  processes  may  be  appropriate  is  when  building   a  music  player  that  plays  music  from  a  service  for  long  period  of  8me.   Managing  Your  App's  Memory   hkp://developer.android.com/training/ar8cles/memory.html   Good  Prac8ce!  J  
  23. Tip  J   How  to  debug  mul8ple  processes  in  Eclipse

      Open  DDMS  perspec8ve     (Window  menu  à  Open  Perspec8ve  à  Other…  then  select  DDMS).   1º   2º   23/41  
  24. Ac8vity   Main   Thread          

          Looper   Message   Queue   Syst.   Events   UI   Events   Service   Handler   Thread                 Looper   Message   Queue   Process   Applica8on  /  APK  Package   Example:  Service  +  HandlerThread  /  1  Process   24/41   HandlerThread  inherits  from  Thread  and  encapsulates  a  Looper-­‐object.   Is  a  Thread  with  a  message  queue  and  processing  loop.   hkps://github.com/josejuansanchez/GDG-­‐DevFestSur-­‐2013/tree/master/LocalServiceHandlerThread    
  25. Don’t  forget  it!!   25/41   Example:  Service  +  HandlerThread

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

  27. Example:  Service  +  HandlerThread  /  1  Process   27/41  

  28. 28/41  

  29. Ac8vity   Main   Thread          

          Looper   Message   Queue   Syst.   Events   UI   Events   IntentService   Worker   Thread                 Looper   Message   Queue   Process   Applica8on  /  APK  Package   Example:  IntentService  /  1  Process   29/41   IntentService  is  the  best  op#on  if  you  don't  require  that   your  service  handle  mul8ple  requests  simultaneously   hkps://github.com/josejuansanchez/GDG-­‐DevFestSur-­‐2013/tree/master/IntentService    
  30. Example.  IntentService  /  1  Process   30/41   You  never

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

  32. Example:  IntentService  Remote  /  2  Processes   32/41   IntentService

     is  the  best  op#on  if  you  don't  require  that   your  service  handle  mul8ple  requests  simultaneously   Ac8vity   Main   Thread                 Looper   Message   Queue   Syst.   Events   UI   Events   IntentService   Worker   Thread                 Looper   Message   Queue   Syst.   Events   Process   Process   Applica8on  /  APK  Package   hkps://github.com/josejuansanchez/GDG-­‐DevFestSur-­‐2013/tree/master/IntentServiceRemote    
  33. 33/41  

  34. 34/41   hkps://android.googlesource.com/plaworm/frameworks/base/+/master/core/java/android/app/ IntentService.java     Read  the  Code!  

    Tip  J   to  understand  how  the  IntentService  works  
  35. 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  communica8on  to  Main   Thread.  This  is  the  best  op8on  if  you  don't  require  that  your  service  handle  mul8ple   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  applica8on.   •  The  IntentService  runs  on  a  separate  Worker  Thread.     4)  Limita#ons  /  Drawbacks   •  The  Service  may  block  the  Main  Thread  of  the  applica8on.   •  The  IntentService  cannot  run  tasks  in  parallel.   Service  vs  IntentService   35/41  
  36. There  are  several  ways  to  get  results  from  a  Service

     back  to  an  invoking  Ac8vity:   •  Broadcast  Intents              This  requires  having  the  Ac8vity  register  a  BroadcastReceiver.   •  Messenger  object              This  object  can  send  messages  to  an  Ac8vity’s  Handler.   •  Pending  Intent              Using  a  Pending  Intent  to  trigger  a  call  to  Ac8vity’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.   Communica8ng  from  Services   36/41  
  37. 37/41   Example:  IntentService  and  Broadcast  Receiver/  1  Process  

    1.  registerReceiver   mIntentReceiver   mIntentFilter   onReceive()   3.  onReceive     BroadcastReceiver   Ac8vity   IntentService                   Ac8vityManagerService             2.  sendBroadcast   IntentService   hkps://github.com/josejuansanchez/GDG-­‐DevFestSur-­‐2013/tree/master/IntentServiceBR    
  38. Process   Applica8on  /  APK  Package   Bound  Services  

    38/41  
  39. Ac8vity             Main   Thread

                    Looper   Message   Queue   RemoteService   Process   Process   Applica8on  A  /  APK  Package   Example:  Remote  Bound  Services   39/41   RemoteBinder         getRandomNumber()   Applica8on  B  /  APK  Package   mBound   1.  Call  method   2.  Return  results   to  caller   Binder  IPC   Mechanism   We  need  interprocess  communica8on  (IPC)  
  40. Ac8vity             Main   Thread

                    Looper   Message   Queue   RemoteService   Process   Applica8on  A  /  APK  Package   Example:  Locally  Bound  Services   40/41   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  
  41.       José  Juan  Sánchez  Hernández   @josejuansanchez  

    Viernes  Androides