Android Services and Background Tasks

Android Services and Background Tasks

Presentación utilizada en el XV Betabeers Almería. 25 de Marzo de 2014.

http://betabeers.com/event/xv-betabeers-almeria-1691

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.

Transcript

  1. Android  Services     &   Background  Tasks    

        José  Juan  Sánchez  Hernández   @josejuansanchez  
  2. Ac<vi<es   Ac<vi<es   Ac<vi<es   Ac<vi<es   Ac<vi<es  

    Services   Ac<vi<es   Ac<vi<es   Receivers   Ac<vi<es   Ac<vi<es   Providers   Dalvik  VM   Libs   DB   Files   res   Android  Applica<on  Anatomy   Process   Applica<on  /  APK  Package   Applica<on  =  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  na<ve  libraries.     •  No  other  app  can  access  any  of  its   data  without  prior  permission.   2/50  
  3. Process   Applica<on  /  APK  Package   Run<me  Overview  with

     Dalvik  VM   Image:  Marko  Gargenta   Android  Internals  Overview   3/50  
  4. $  adb  shell  ps   USER PID PPID VSIZE RSS

    WCHAN PC NAME ... u0_a87 6229 1940 516552 31484 ffffffff 00000000 S com.android.calendar u0_a45 6247 1940 527692 31104 ffffffff 00000000 S com.google.android.calendar system 6276 1940 508328 27496 ffffffff 00000000 S com.sec.android.app.mt system 6292 1940 508644 27284 ffffffff 00000000 S com.sec.android.app.popupuir system 6306 1940 509388 28020 ffffffff 00000000 S com.sec.android.app.SecSetup system 6320 1940 515244 33816 ffffffff 00000000 S com.wssyncmldm u0_a54 6336 1940 510468 27460 ffffffff 00000000 S com.sec.android.app.controlp u0_a118 6350 1940 508704 28976 ffffffff 00000000 S com.sec.android.daemonapp.ap u0_a158 6362 1940 509020 29216 ffffffff 00000000 S com.sec.android.sCloudSync u0_a83 6375 1940 516300 36124 ffffffff 00000000 S com.osp.app.signin u0_a142 6393 1940 514340 32592 ffffffff 00000000 S com.google.android.keep u0_a10 6414 1940 508428 28252 ffffffff 00000000 S com.sec.android.provider.sme u0_a85 6427 1940 518356 30832 ffffffff 00000000 S com.android.browser u0_a50 6474 1940 533152 43816 ffffffff 00000000 S com.google.android.tts ... Zygote   4/50   $  adb  shell  ps  zygote   USER PID PPID VSIZE RSS WCHAN PC NAME root 1940 1 500544 22144 ffffffff 00000000 S zygote
  5. The  manifest  entry  for  each  type  of  component  element:  

        <activity>, <service>,  <receiver>  and  <provider>     supports  an  android:process  a_ribute  that  can  specify  a  process  in  which  that   component  should  run.  You  can  set  this  a_ribute  so  that  each  component  runs  in  its   own  process  or  so  that  some  components  share  a  process  while  others  do  not.       You  can  also  set  android:process  so  that  components  of  different  applica<ons   run  in  the  same  process—provided  that  the  applica<ons  share  the  same  Linux  user  ID   and  are  signed  with  the  same  cer<ficates.     The  <application>  element  also  supports  an  android:process  a_ribute,  to   set  a  default  value  that  applies  to  all  components.     Processes   5/50  
  6. Process   Applica<on  /  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.     Processes  and  Threads   6/61  
  7. Ac<vity   Service   Main  Thread        

            Looper   Message   Queue   System   Events   UI   Events   Process   Applica<on  /  APK  Package   Understanding  the  UI  Thread   7/50  
  8. UI   Thread   Background  Threads   8/50   UI

      Thread   BG   Thread   BG   Thread   2.  Do  long     running  task   1   1   2.  Do  long     running  task   3.  Report  result  or  update  UI  
  9. Android  Scheduling   9/50   Process  rank     1. 

    Foreground     2.  Visible     3.  Service     4.  Background     5.  Empty     Foreground  Thread  Group   App  A   Background  Thread  Group   App  A   >  90  %   <  10  %   CPU  execu<on  <me   CPU  execu<on  <me   Source:  Efficient  Android  Threading  /  Anders  Göransson  
  10. Android  Scheduling   10/50   Source:  Efficient  Android  Threading  /

     Anders  Göransson   Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); Low  background  thread  priority  =  Be_er  responsiveness  
  11. Asynchronous  Techniques   11/50   •  Thread   •  Executor

      •  Handler  Thread   •  AsyncTask   •  IntentService   •  AsyncQueryHandler   •  Loader       Thread   Handler   Thread     Executor     Intent   Service   Async   Query   Handler   Loader   Async   Task   Source:  Efficient  Android  Threading  /  Anders  Göransson  
  12. Lifecycles  and  Memory  Leaks   12/50   Time   Ac<vity

      Component   onCreate()   onDestroy()   Ac<vity   Object   new()   GC   Source:  Efficient  Android  Threading  /  Anders  Göransson   Example  
  13. Lifecycles  and  Memory  Leaks   13/50   Time   Ac<vity

      Component   onCreate()   onDestroy()   onCreate()   onDestroy()   Ac<vity   Object   new()   GC   Ac<vity   Object   new()   GC   Source:  Efficient  Android  Threading  /  Anders  Göransson   Example  
  14. Lifecycles  and  Memory  Leaks   14/50   Time   Ac<vity

      Component   onCreate()   onDestroy()   onCreate()   onDestroy()   Ac<vity   Object   new()   Ac<vity   Object   new()   Start   BG   Reference   Source:  Efficient  Android  Threading  /  Anders  Göransson   Example  
  15. 15/50   Time   Lifecycles  and  Memory  Leaks   Source:

     Efficient  Android  Threading  /  Anders  Göransson   Avoid  Memory  Leaks     •  Short  tasks.   •  Cancella<on  policy.   •  Retain  tasks.   •  Low  memory  references.   •  Avoid  defining  threads  as  inner  or  anonymous  classes.      
  16. Applica<on  /  APK  Package   16/50   Time   Ac<vity

      Component   onCreate()   onDestroy()   onCreate()   onDestroy()   Service   Component   onCreate()   onDestroy()   BG   Lifecycles  and  Memory  Leaks   Source:  Efficient  Android  Threading  /  Anders  Göransson   Example:  Lifecycle  Decoupling  
  17. Applica<on  /  APK  Package   Services   17/50  

  18. Services   18/50   What  is  a  Service?   • 

    Is  a  component  that  can  perform  long-­‐running  opera<ons  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  ac<vity  gets  garbage-­‐collected.   •  Polling  the  Internet  for  RSS/Atom  feed  updates.   •  Performing  periodic  work  without  user  interven<on  (scheduled  tasks).   •  An  applica<on  that  con<nually  logs  the  geographical  coordinates  of  the  device.    
  19. Process   Applica<on  /  APK  Package   Started   A

     service  is  “started”  when  an   applica<on  component  starts  it  by   calling  startService().  Owen   performs  a  single  opera<on  &  might   not  return  a  result  to  the  caller   directly.     Bound   A  service  is  “bound”  when  an   applica<on  component  binds  to  it  by   calling  bindService().  Provides  a   client-­‐  server  interface  that  allows  for   a  conversa<on  with  the  Service.   Types  of  Services   Android  Developers.  API  Guides   h_ps://developer.android.com/guide/components/services.html   19/50  
  20. Applica<on  /  APK  Package   Started  Services   There  are

     two  classes  you  can  extend  to  create  a  started  service:   Service  and  IntentService     20/50  
  21. Ac<vity   Service   Main  Thread        

            Looper   Message   Queue   System   Events   UI   Events   Process   Applica<on  /  APK  Package   Example:  LocalService  /  1  Process   21/50   A  long  task  may  block  the  Main  Thread  !   h_ps://github.com/josejuansanchez/GDG-­‐DevFestSur-­‐2013/tree/master/LocalService  
  22. Example:  LocalService  /  1  Process   22/50  

  23. Example:  LocalService  /  1  Process   23/50  

  24. The  service  should  remain  stopped  un<l     explicitly  started

     by  applica<on  code   24/50  
  25. Example:  LocalService  /  1  Process   25/50   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  op<on  to  avoid  running  your  service  when  not  necessary  and   when  your  applica<on  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  execu<ng   commands,  but  running  indefinitely  and  wai<ng  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  ac<vely  performing  a  job  that  should  be  immediately   resumed,  such  as  downloading  a  file.  
  26. Don’t  forget  it!!   26/50  

  27. Good  Prac<ce!  ☺   27/50   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   h_p://developer.android.com/training/ar<cles/memory.html   Use  services  sparingly   stopSelf();  
  28. Example:  LocalService  /  1  Process   28/50  

  29. 29/50  

  30. Ac<vity   Main   Thread          

          Looper   Message   Queue   Syst.   Events   UI   Events   Service   Main   Thread                 Looper   Message   Queue   Syst.   Events   Process   Process   Applica<on  /  APK  Package   Example:  RemoteService  /  2  Processes   30/50   “Remote”  in  this  example  means  that  the  Service  is  hosted  in  another  process.   h_ps://github.com/josejuansanchez/GDG-­‐DevFestSur-­‐2013/tree/master/RemoteService    
  31. Example:  RemoteService  /  2  Processes   31/50  

  32. Example:  RemoteService  /  2  Processes   32/50  

  33. This  technique  must  always  be  used  carefully  and    

    most  apps  should  not  run  mul#ple  processes   33/50   You  can  use  mul<ple  processes*   An  advanced  technique  that  may  help  you  manage  your  app's  memory  is   dividing  components  of  your  app  into  mul<ple  processes.       An  example  of  when  mul<ple  processes  may  be  appropriate  is  when  building   a  music  player  that  plays  music  from  a  service  for  long  period  of  <me.   Managing  Your  App's  Memory   h_p://developer.android.com/training/ar<cles/memory.html   *  
  34. Tip  ☺   How  to  debug  mul<ple  processes  in  Eclipse

      Open  DDMS  perspec<ve     (Window  menu  #  Open  Perspec<ve  #  Other…  then  select  DDMS).   1º   2º   34/50  
  35. 35/50   Process  rank:  Foreground     $  adb  shell

     ps  |  grep  "com.google.android.music"   USER                  PID              PPID    VSIZE          RSS          WCHAN        PC                    NAME   u0_a137      17837  1940    604896  64268  ffffffff  00000000  S  com.google.android.music:ui   u0_a137      17854  1940    553744  39768  ffffffff  00000000  S  com.google.android.music:main   Example:  Google  Play  Music   Process  rank:  Visible  
  36. Ac<vity   Main   Thread          

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

     /  1  Process  
  38. 38/50   Example:  Service  +  HandlerThread  /  1  Process  

  39. Example:  Service  +  HandlerThread  /  1  Process   39/50  

  40. 40/50  

  41. Ac<vity   Main   Thread          

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

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

  44. 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  communica<on  to  Main   Thread.  This  is  the  best  op<on  if  you  don't  require  that  your  service  handle  mul<ple   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  applica<on.   •  The  IntentService  runs  on  a  separate  Worker  Thread.     4)  Limita#ons  /  Drawbacks   •  The  Service  may  block  the  Main  Thread  of  the  applica<on.   •  The  IntentService  cannot  run  tasks  in  parallel.     Service  vs  IntentService   44/50  
  45. There  are  several  ways  to  get  results  from  a  Service

     back  to  an  invoking  Ac<vity:   •  Broadcast  Intents              This  requires  having  the  Ac<vity  register  a  BroadcastReceiver.   •  Messenger  object              This  object  can  send  messages  to  an  Ac<vity’s  Handler.   •  Pending  Intent              Using  a  Pending  Intent  to  trigger  a  call  to  Ac<vity’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.   Communica<ng  from  Services   45/50  
  46. 46/50   Example:  IntentService  and  Broadcast  Receiver   1.  registerReceiver

      mIntentReceiver   mIntentFilter   onReceive()   3.  onReceive     BroadcastReceiver   Ac<vity   IntentService                   Ac<vityManagerService             2.  sendBroadcast   IntentService   h_ps://github.com/josejuansanchez/GDG-­‐DevFestSur-­‐2013/tree/master/IntentServiceBR    
  47. Process   Applica<on  /  APK  Package   Bound  Services  

    47/50  
  48. Ac<vity             Main   Thread

                    Looper   Message   Queue   RemoteService   Process   Process   Applica<on  A  /  APK  Package   Example:  Remote  Bound  Services   48/50   RemoteBinder         getRandomNumber()   Applica<on  B  /  APK  Package   mBound   1.  Call  method   2.  Return  results   to  caller   Binder  IPC   Mechanism   We  need  interprocess  communica<on  (IPC)  
  49. Ac<vity             Main   Thread

                    Looper   Message   Queue   RemoteService   Process   Applica<on  A  /  APK  Package   Example:  Locally  Bound  Services   49/50   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  
  50. Android  Services     &   Background  Tasks    

        José  Juan  Sánchez  Hernández   @josejuansanchez