Upgrade to Pro — share decks privately, control downloads, hide ads and more …

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.

More Decks by José Juan Sánchez Hernández

Other Decks in Programming

Transcript

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

    View Slide

  2. AcAcAcAcAcServices  
    AcAcReceivers  
    AcAcProviders  
    Dalvik  VM  
    Libs  
    DB  
    Files  
    res  
    Android  ApplicaProcess  
    ApplicaApplica  
    •  It  contains  any  number  of  Ac#vi#es,  
    Services,  Receivers  and  Providers.  
     
    •  It  has  its  own  file  system,  database,  
    place  to  store  na  
    •  No  other  app  can  access  any  of  its  
    data  without  prior  permission.  
    2/50  

    View Slide

  3. Process  
    ApplicaRunImage:  Marko  Gargenta  
    Android  Internals  Overview  
    3/50  

    View Slide

  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

    View Slide

  5. The  manifest  entry  for  each  type  of  component  element:    
     
    , ,    and    
     
    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  applicarun  in  the  same  process—provided  that  the  applicaand  are  signed  with  the  same  cer<ficates.  
     
    The    element  also  supports  an  android:process  a_ribute,  to  
    set  a  default  value  that  applies  to  all  components.  
     
    Processes  
    5/50  

    View Slide

  6. Process  
    ApplicaProcess  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  

    View Slide

  7. AcService  
    Main  Thread  
     
     
     
     
     
     
     
    Looper  
    Message  
    Queue  
    System  
    Events  
    UI  
    Events  
    Process  
    ApplicaUnderstanding  the  UI  Thread  
    7/50  

    View Slide

  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  

    View Slide

  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  execuCPU  execuSource:  Efficient  Android  Threading  /  Anders  Göransson  

    View Slide

  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  

    View Slide

  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  

    View Slide

  12. Lifecycles  and  Memory  Leaks  
    12/50  
    Time  
    AcComponent  
    onCreate()   onDestroy()  
    AcObject  
    new()   GC  
    Source:  Efficient  Android  Threading  /  Anders  Göransson  
    Example  

    View Slide

  13. Lifecycles  and  Memory  Leaks  
    13/50  
    Time  
    AcComponent  
    onCreate()   onDestroy()   onCreate()   onDestroy()  
    AcObject  
    new()   GC  
    AcObject  
    new()   GC  
    Source:  Efficient  Android  Threading  /  Anders  Göransson  
    Example  

    View Slide

  14. Lifecycles  and  Memory  Leaks  
    14/50  
    Time  
    AcComponent  
    onCreate()   onDestroy()   onCreate()   onDestroy()  
    AcObject  
    new()  
    AcObject  
    new()  
    Start  
    BG  
    Reference  
    Source:  Efficient  Android  Threading  /  Anders  Göransson  
    Example  

    View Slide

  15. 15/50  
    Time  
    Lifecycles  and  Memory  Leaks  
    Source:  Efficient  Android  Threading  /  Anders  Göransson  
    Avoid  Memory  Leaks  
     
    •  Short  tasks.  
    •  Cancella•  Retain  tasks.  
    •  Low  memory  references.  
    •  Avoid  defining  threads  as  inner  or  anonymous  classes.  
     
     

    View Slide

  16. Applica16/50  
    Time  
    AcComponent  
    onCreate()   onDestroy()   onCreate()   onDestroy()  
    Service  
    Component  
    onCreate()   onDestroy()  
    BG  
    Lifecycles  and  Memory  Leaks  
    Source:  Efficient  Android  Threading  /  Anders  Göransson  
    Example:  Lifecycle  Decoupling  

    View Slide

  17. ApplicaServices  
    17/50  

    View Slide

  18. Services  
    18/50  
    What  is  a  Service?  
    •  Is  a  component  that  can  perform  long-­‐running  opera•  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•  Polling  the  Internet  for  RSS/Atom  feed  updates.  
    •  Performing  periodic  work  without  user  interven•  An  applica  

    View Slide

  19. Process  
    ApplicaStarted  
    A  service  is  “started”  when  an  
    applicacalling  startService().  Owen  
    performs  a  single  operanot  return  a  result  to  the  caller  
    directly.  
     
    Bound  
    A  service  is  “bound”  when  an  
    applicacalling  bindService().  Provides  a  
    client-­‐  server  interface  that  allows  for  
    a  conversaTypes  of  Services  
    Android  Developers.  API  Guides  
    h_ps://developer.android.com/guide/components/services.html  
    19/50  

    View Slide

  20. ApplicaStarted  Services  
    There  are  two  classes  you  can  extend  to  create  a  started  service:  
    Service  and  IntentService  
     
    20/50  

    View Slide

  21. AcService  
    Main  Thread  
     
     
     
     
     
     
     
    Looper  
    Message  
    Queue  
    System  
    Events  
    UI  
    Events  
    Process  
    ApplicaExample:  LocalService  /  1  Process  
    21/50  
    A  long  task  may  block  the  Main  Thread  !  
    h_ps://github.com/josejuansanchez/GDG-­‐DevFestSur-­‐2013/tree/master/LocalService  

    View Slide

  22. Example:  LocalService  /  1  Process  
    22/50  

    View Slide

  23. Example:  LocalService  /  1  Process  
    23/50  

    View Slide

  24. The  service  should  remain  stopped  unexplicitly  started  by  applica24/50  

    View Slide

  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  opwhen  your  applica  
    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  execucommands,  but  running  indefinitely  and  wai  
    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  acresumed,  such  as  downloading  a  file.  

    View Slide

  26. Don’t  forget  it!!  
    26/50  

    View Slide

  27. Good  Prac27/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/arUse  services  sparingly  
    stopSelf();  

    View Slide

  28. Example:  LocalService  /  1  Process  
    28/50  

    View Slide

  29. 29/50  

    View Slide

  30. AcMain  
    Thread  
     
     
     
     
     
     
     
    Looper  
    Message  
    Queue  
    Syst.  
    Events  
    UI  
    Events  
    Service  
    Main  
    Thread  
     
     
     
     
     
     
     
    Looper  
    Message  
    Queue  
    Syst.  
    Events  
    Process   Process  
    ApplicaExample:  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  
     

    View Slide

  31. Example:  RemoteService  /  2  Processes  
    31/50  

    View Slide

  32. Example:  RemoteService  /  2  Processes  
    32/50  

    View Slide

  33. This  technique  must  always  be  used  carefully  and    
    most  apps  should  not  run  mul#ple  processes  
    33/50  
    You  can  use  mulAn  advanced  technique  that  may  help  you  manage  your  app's  memory  is  
    dividing  components  of  your  app  into  mul  
    An  example  of  when  mula  music  player  that  plays  music  from  a  service  for  long  period  of  Managing  Your  App's  Memory  
    h_p://developer.android.com/training/ar*  

    View Slide

  34. Tip  ☺  
    How  to  debug  mulOpen  DDMS  perspec(Window  menu  #  Open  Perspec1º  
    2º  
    34/50  

    View Slide

  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  

    View Slide

  36. AcMain  
    Thread  
     
     
     
     
     
     
     
    Looper  
    Message  
    Queue  
    Syst.  
    Events  
    UI  
    Events  
    Service  
    Handler  
    Thread  
     
     
     
     
     
     
     
    Looper  
    Message  
    Queue  
    Process  
    ApplicaExample:  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  
     

    View Slide

  37. Don’t  forget  it!!  
    37/50  
    Example:  Service  +  HandlerThread  /  1  Process  

    View Slide

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

    View Slide

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

    View Slide

  40. 40/50  

    View Slide

  41. AcMain  
    Thread  
     
     
     
     
     
     
     
    Looper  
    Message  
    Queue  
    Syst.  
    Events  
    UI  
    Events  
    IntentService  
    Worker  
    Thread  
     
     
     
     
     
     
     
    Looper  
    Message  
    Queue  
    Process  
    ApplicaExample:  IntentService  /  1  Process  
    41/50  
    IntentService  is  the  best  op#on  if  you  don't  require  that  
    your  service  handle  mulh_ps://github.com/josejuansanchez/GDG-­‐DevFestSur-­‐2013/tree/master/IntentService  
     

    View Slide

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

    View Slide

  43. Example.  IntentService  /  1  Process  
    43/50  

    View Slide

  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  communicaThread.  This  is  the  best  oprequests  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•  The  IntentService  runs  on  a  separate  Worker  Thread.  
     
    4)  Limita#ons  /  Drawbacks  
    •  The  Service  may  block  the  Main  Thread  of  the  applica•  The  IntentService  cannot  run  tasks  in  parallel.  
     
    Service  vs  IntentService  
    44/50  

    View Slide

  45. There  are  several  ways  to  get  results  from  a  Service  back  to  an  invoking  Ac•  Broadcast  Intents  
               This  requires  having  the  Ac•  Messenger  object  
               This  object  can  send  messages  to  an  Ac•  Pending  Intent  
               Using  a  Pending  Intent  to  trigger  a  call  to  Ac  
     
    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.  
    Communica45/50  

    View Slide

  46. 46/50  
    Example:  IntentService  and  Broadcast  Receiver  
    1.  registerReceiver  
    mIntentReceiver  
    mIntentFilter  
    onReceive()  
    3.  onReceive    
    BroadcastReceiver  
    AcIntentService  
     
     
     
     
     
     
     
     
    Ac  
     
     
     
     
    2.  sendBroadcast  
    IntentService  
    h_ps://github.com/josejuansanchez/GDG-­‐DevFestSur-­‐2013/tree/master/IntentServiceBR  
     

    View Slide

  47. Process  
    ApplicaBound  Services  
    47/50  

    View Slide

  48. Ac  
     
     
     
     
    Main  
    Thread  
     
     
     
     
     
     
     
    Looper  
    Message  
    Queue  
    RemoteService  
    Process   Process  
    ApplicaExample:  Remote  Bound  Services  
    48/50  
    RemoteBinder  
     
     
     
    getRandomNumber()  
    ApplicamBound  
    1.  Call  method  
    2.  Return  results  
    to  caller  
    Binder  IPC  
    Mechanism  
    We  need  interprocess  communica

    View Slide

  49. Ac  
     
     
     
     
    Main  
    Thread  
     
     
     
     
     
     
     
    Looper  
    Message  
    Queue  
    RemoteService  
    Process  
    ApplicaExample:  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  

    View Slide

  50. Android  Services    
    &  
    Background  Tasks  
     
     
     
    José  Juan  Sánchez  Hernández  
    @josejuansanchez  

    View Slide