SlideShare a Scribd company logo
1 of 44
Serving your business
                       logically
                                          Dmitry Malykhanov
                                               DataArt



The Android robot is reproduced or modified from work created and shared by Google and used according to terms described in the
Creative Commons 3.0 Attribution License.
First of all
         why we need services
How is it done
              service variants
Then
               start execution
Expedited delivery
          receiving your data
First of all
why exactly we need services
Alternatives

"Just" Code:              Service:

● Thread (pool)
  ○ return to UI thread
● AsyncTask
  ○ serialized
  ○ short lifespan
● Application
                                     ?
  ○ garbage on the heap
  ○ no IPC
Alternatives

"Just" Code:              Service:

● Thread (pool)
  ○ return to UI thread
● AsyncTask
  ○ serialized
  ○ short lifespan
● Application
                                     ?
  ○ garbage on the heap
  ○ no IPC
Alternatives

"Just" Code:              Service:

● Thread (pool)
  ○ return to UI thread
● AsyncTask
  ○ serialized
  ○ short lifespan
● Application
                                     ?
  ○ garbage on the heap
  ○ no IPC
Alternatives

"Just" Code:              Service:

● Thread (pool)           ● Thread/Pool/Etc.
  ○ return to UI thread     ○ flexible control
● AsyncTask               ● Wake Locks
  ○ serialized              ○ guaranteed CPU
  ○ short lifespan        ● Lifetime
● Application               ○ on its own
  ○ garbage on the heap
  ○ no IPC
Alternatives

"Just" Code:              Service:

● Thread (pool)           ● Thread/Pool/Etc.
  ○ return to UI thread     ○ flexible control
● AsyncTask               ● Wake Locks
  ○ serialized              ○ guaranteed CPU
  ○ short lifespan        ● Lifetime
● Application               ○ on its own
  ○ garbage on the heap
  ○ no IPC
Alternatives

"Just" Code:              Service:

● Thread (pool)           ● Thread/Pool/Etc.
  ○ return to UI thread     ○ flexible control
● AsyncTask               ● Wake Locks
  ○ serialized              ○ guaranteed CPU
  ○ short lifespan        ● Lifetime
● Application               ○ on its own
  ○ garbage on the heap
  ○ no IPC
What's the price?



●   IPC
●   Resources
●   Security
What's the price?



           ●   IPC
           ●   Resources
           ●   SECURITY
AndroidManifest.xml:

       <service ... android:exported="false" />
How it is done
service kinds and variants
Simple service

IntentService:


● single thead
● requested enqueued
● clear lifecycle



http://goo.gl/TvtbV
Cloning simple services

Two/three tasks at the same time:

<service android:name=".FirstIntentService" />

<service android:name=".SecondIntentService" />

<service android:name=".ThirdIntentService" />
Complex services

ExecutorService:

● ThreadPoolExecutor
● Scheduled
   ThreadPoolExecutor



http://goo.gl/mwV90
Lifecycle: issue

IntentService             ThreadPoolService

                                   ?
Lifecycle: solution

 startId -> ConcurrentLinkedQueue

                     requests: 1, 2, 3, 4, 5
Thread      1           3        4      4       4     idle
Thread      2           2        2      5      idle   idle


Queue    1,2,3,4,5    2,3,4,5   3,4,5   4, 5    5     STOP
Then
start the proper execution
What and how?

switch (cmdId) {
   case CMD_POLL:
      poll();          How to expand?
      break;
   case CMD_UPLOAD:
      upload();
      break;
                  if ("poll".equals(cmd)) {
                     poll();
                  } else if ("upload".equals(cmd)) {
                     upload();
                  }
Independence

GoF: Command Pattern


interface Command {

    void execute(Context);

}                              4
http://goo.gl/hwFY9
Unique IDs

public static final int CMD_POLL = 10;
public static final int CMD_UPLOAD = 20;
...




               Command.class.hashCode()

               System.identityHashCode()
Commands delivery

switch (commandId) {
    case CMD_POLL:
        return new PollCommand().execute();
    case CMD_UPLOAD:
        return new UploadCommand().execute();
...


  abstract class Command
      implements Parcelable {

      public abstract void execute(...);
  }
Out of band execution

Serialize/prioritize commands, e.g.:

                 Command.isSerial()

frameworks/base/core/java/android/os/AsyncTask.java:



private static class SerialExecutor
    implements Executor {
...
Expedited delivery
receiving your data
Wrapping the data


    ●   Entity Bean




●       android.os.Bundle
Wrapping the data


    ●   Entity Bean
          YES: type-safe
            ○

          NO: CPU cycles
            ○

          NO: IPC
            ○



●       android.os.Bundle
        ○ YES: no type conversion
        ○ NO: Parcelable only
Wrapping the data


    ●   Entity Bean
          YES: type-safe
            ○

          NO: CPU cycles
            ○

          NO: IPC
            ○



●       android.os.Bundle
        ○ YES: no type conversion
        ○ NO: Parcelable only
Universal container



public class EntityBean
         implements Parcelable
{
...




http://goo.gl/QSFPe
Serializable? No way!

Serializable - the best of all?

           Parcelable

      ^
                              Parcelable
      S
      p
                              5..10 times
      e
      e
                               FASTER!
      d
      ^
          Serializable
One way ticket

Delivery transport:
  ● broadcast

Issues:
   ● IPC
   ● wakelock
   ● receiver's lifecycle

                      LocalBroadcastManager
http://goo.gl/2h80u
Batch them

Delivery transport:
  ● database (provider)

Issues:
   ● delays
   ● notification "storm"




http://goo.gl/ZPoei
Messenger bag

Delivery transport:
  ● singleton

Issue:
   ● single process
   ● memory consumption
   ● tight coupling



http://goo.gl/yfHPn   http://goo.gl/5AR9h
Courier delivery

import android.os.ResultReceiver;
  private ResultReceiver receiver =
       new ResultReceiver(handler) {
         ...
       }
...
  new PollCommand(receiver)
       .start(...);

http://goo.gl/rwhw0
Zombie-problem

                 Receiver           Sender

 Activity                       Service




                Receiver           Sender
                                              onDestroy
 Activity                       Service




                    Receiver

     Activity
                Receiver             Sender
                                   Sender
                                              onCreate
Activity                       Service
Eternal life
Application
                  Receiver

                                Sender

                             Service

  Activity




Application
                  Receiver

                                Sender

                             Service

  Activity
       Activity
Eternal life: problems
Application
              Receiver

                            Sender
                 ?
                         Service

  Activity



                          Garbage
                          Collected
Application
              Receiver

                            Sender

                         Service

  Activity
Life without problems


Application                                     Buffer

              Receiver


                                                Sender




                                      Service




        Activity
Smooth: UI Thread


private ResultReceiver receiver =
  new ResultReceiver(new Handler()) {
    ...
  }


      UI Thread!
Smooth: Background

private Handler handler =
  new Handler(handlerThread);

private ResultReceiver receiver =
  new ResultReceiver(handler) {
    ... onReceive(...) {
       ...
       runOnUiThread(...)
                                  UI
    }
  }
Smooth: altogether


private ResultReceiver receiverUi =
  new ResultReceiver(uiThrdHandler) {
    ...
  }

private ResultReceiver receiverBg =
  new ResultReceiver(bgThrdHandler) {
    ...
  }
Best of both worlds
  join all in one
Universal all-in-one service



          GC
                        AIDL Binder

    Queue              get(id)
                   submit(id, command)
    Receiver

                  Command
                     Command
Service
Serving your business
       logically
     Dmitry Malykhanov

     Questions?
Serving your business
                       logically




The Android robot is reproduced or modified from work created and shared by Google and used according to terms described in the
Creative Commons 3.0 Attribution License.

More Related Content

What's hot

A synchronous scheduling service for distributed real-time Java
A synchronous scheduling service for distributed real-time JavaA synchronous scheduling service for distributed real-time Java
A synchronous scheduling service for distributed real-time JavaUniversidad Carlos III de Madrid
 
Java 7 - New Features - by Mihail Stoynov and Svetlin Nakov
Java 7 - New Features - by Mihail Stoynov and Svetlin NakovJava 7 - New Features - by Mihail Stoynov and Svetlin Nakov
Java 7 - New Features - by Mihail Stoynov and Svetlin NakovSvetlin Nakov
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals ThreadsNeera Mital
 
OpenGL NVIDIA Command-List: Approaching Zero Driver Overhead
OpenGL NVIDIA Command-List: Approaching Zero Driver OverheadOpenGL NVIDIA Command-List: Approaching Zero Driver Overhead
OpenGL NVIDIA Command-List: Approaching Zero Driver OverheadTristan Lorach
 
Twisted Introduction
Twisted IntroductionTwisted Introduction
Twisted Introductioncyli
 
Simple asynchronous remote invocations for distributed real-time Java
Simple asynchronous remote invocations for distributed real-time JavaSimple asynchronous remote invocations for distributed real-time Java
Simple asynchronous remote invocations for distributed real-time JavaUniversidad Carlos III de Madrid
 
Experiments in Sharing Java VM Technology with CRuby
Experiments in Sharing Java VM Technology with CRubyExperiments in Sharing Java VM Technology with CRuby
Experiments in Sharing Java VM Technology with CRubyMatthew Gaudet
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 
Achieving Performance Zen with YUI 3
Achieving Performance Zen with YUI 3Achieving Performance Zen with YUI 3
Achieving Performance Zen with YUI 3Ryan Grove
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsRobert Brown
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twistedsdsern
 
Jvm Performance Tunning
Jvm Performance TunningJvm Performance Tunning
Jvm Performance Tunningguest1f2740
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS MultithreadingRicha Jain
 
Qt everywhere a c++ abstraction platform
Qt everywhere   a c++ abstraction platformQt everywhere   a c++ abstraction platform
Qt everywhere a c++ abstraction platformDeveler S.r.l.
 
Using Grails to Power your Electric Car
Using Grails to Power your Electric CarUsing Grails to Power your Electric Car
Using Grails to Power your Electric CarGR8Conf
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?hawkowl
 
Twisted: a quick introduction
Twisted: a quick introductionTwisted: a quick introduction
Twisted: a quick introductionRobert Coup
 

What's hot (20)

A synchronous scheduling service for distributed real-time Java
A synchronous scheduling service for distributed real-time JavaA synchronous scheduling service for distributed real-time Java
A synchronous scheduling service for distributed real-time Java
 
Java 7 - New Features - by Mihail Stoynov and Svetlin Nakov
Java 7 - New Features - by Mihail Stoynov and Svetlin NakovJava 7 - New Features - by Mihail Stoynov and Svetlin Nakov
Java 7 - New Features - by Mihail Stoynov and Svetlin Nakov
 
Qt Framework Events Signals Threads
Qt Framework Events Signals ThreadsQt Framework Events Signals Threads
Qt Framework Events Signals Threads
 
OpenGL NVIDIA Command-List: Approaching Zero Driver Overhead
OpenGL NVIDIA Command-List: Approaching Zero Driver OverheadOpenGL NVIDIA Command-List: Approaching Zero Driver Overhead
OpenGL NVIDIA Command-List: Approaching Zero Driver Overhead
 
Twisted Introduction
Twisted IntroductionTwisted Introduction
Twisted Introduction
 
Simple asynchronous remote invocations for distributed real-time Java
Simple asynchronous remote invocations for distributed real-time JavaSimple asynchronous remote invocations for distributed real-time Java
Simple asynchronous remote invocations for distributed real-time Java
 
Experiments in Sharing Java VM Technology with CRuby
Experiments in Sharing Java VM Technology with CRubyExperiments in Sharing Java VM Technology with CRuby
Experiments in Sharing Java VM Technology with CRuby
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency Idioms
 
Achieving Performance Zen with YUI 3
Achieving Performance Zen with YUI 3Achieving Performance Zen with YUI 3
Achieving Performance Zen with YUI 3
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design Patterns
 
An Introduction to Twisted
An Introduction to TwistedAn Introduction to Twisted
An Introduction to Twisted
 
Jvm Performance Tunning
Jvm Performance TunningJvm Performance Tunning
Jvm Performance Tunning
 
Enhancing the region model of RTSJ
Enhancing the region model of RTSJEnhancing the region model of RTSJ
Enhancing the region model of RTSJ
 
iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS Multithreading
 
Qt everywhere a c++ abstraction platform
Qt everywhere   a c++ abstraction platformQt everywhere   a c++ abstraction platform
Qt everywhere a c++ abstraction platform
 
How we use Twisted in Launchpad
How we use Twisted in LaunchpadHow we use Twisted in Launchpad
How we use Twisted in Launchpad
 
Using Grails to Power your Electric Car
Using Grails to Power your Electric CarUsing Grails to Power your Electric Car
Using Grails to Power your Electric Car
 
WTF is Twisted?
WTF is Twisted?WTF is Twisted?
WTF is Twisted?
 
Qt Quick in depth
Qt Quick in depthQt Quick in depth
Qt Quick in depth
 
Twisted: a quick introduction
Twisted: a quick introductionTwisted: a quick introduction
Twisted: a quick introduction
 

Viewers also liked

Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!Stacy Devino
 
Functional Reactive Programming on Android
Functional Reactive Programming on AndroidFunctional Reactive Programming on Android
Functional Reactive Programming on AndroidSam Lee
 
Performance #6 threading
Performance #6  threadingPerformance #6  threading
Performance #6 threadingVitali Pekelis
 
Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskAndroid - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskHoang Ngo
 

Viewers also liked (6)

Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!Async task, threads, pools, and executors oh my!
Async task, threads, pools, and executors oh my!
 
Functional Reactive Programming on Android
Functional Reactive Programming on AndroidFunctional Reactive Programming on Android
Functional Reactive Programming on Android
 
Android concurrency
Android concurrencyAndroid concurrency
Android concurrency
 
Performance #6 threading
Performance #6  threadingPerformance #6  threading
Performance #6 threading
 
Android - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTaskAndroid - Thread, Handler and AsyncTask
Android - Thread, Handler and AsyncTask
 
Efficient Android Threading
Efficient Android ThreadingEfficient Android Threading
Efficient Android Threading
 

Similar to UA Mobile 2012 (English)

Kandroid for nhn_deview_20131013_v5_final
Kandroid for nhn_deview_20131013_v5_finalKandroid for nhn_deview_20131013_v5_final
Kandroid for nhn_deview_20131013_v5_finalNAVER D2
 
Spring cloud for microservices architecture
Spring cloud for microservices architectureSpring cloud for microservices architecture
Spring cloud for microservices architectureIgor Khotin
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server InternalsPraveen Gollakota
 
ควบคุมบอร์ดArduinoผ่านระบบandroid
ควบคุมบอร์ดArduinoผ่านระบบandroidควบคุมบอร์ดArduinoผ่านระบบandroid
ควบคุมบอร์ดArduinoผ่านระบบandroidWorakrit Sittirit
 
Android Jetpack + Coroutines: To infinity and beyond
Android Jetpack + Coroutines: To infinity and beyondAndroid Jetpack + Coroutines: To infinity and beyond
Android Jetpack + Coroutines: To infinity and beyondRamon Ribeiro Rabello
 
Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...Opersys inc.
 
Build microservice with gRPC in golang
Build microservice with gRPC in golangBuild microservice with gRPC in golang
Build microservice with gRPC in golangTing-Li Chou
 
OWF12/PAUG Conf Days Android tools for developpeurs, paul marois, design and ...
OWF12/PAUG Conf Days Android tools for developpeurs, paul marois, design and ...OWF12/PAUG Conf Days Android tools for developpeurs, paul marois, design and ...
OWF12/PAUG Conf Days Android tools for developpeurs, paul marois, design and ...Paris Open Source Summit
 
Norikra: SQL Stream Processing In Ruby
Norikra: SQL Stream Processing In RubyNorikra: SQL Stream Processing In Ruby
Norikra: SQL Stream Processing In RubySATOSHI TAGOMORI
 
Monitoring as Code: Getting to Monitoring-Driven Development - DEV314 - re:In...
Monitoring as Code: Getting to Monitoring-Driven Development - DEV314 - re:In...Monitoring as Code: Getting to Monitoring-Driven Development - DEV314 - re:In...
Monitoring as Code: Getting to Monitoring-Driven Development - DEV314 - re:In...Amazon Web Services
 
[KubeCon EU 2020] containerd Deep Dive
[KubeCon EU 2020] containerd Deep Dive[KubeCon EU 2020] containerd Deep Dive
[KubeCon EU 2020] containerd Deep DiveAkihiro Suda
 

Similar to UA Mobile 2012 (English) (20)

Edge architecture ieee international conference on cloud engineering
Edge architecture   ieee international conference on cloud engineeringEdge architecture   ieee international conference on cloud engineering
Edge architecture ieee international conference on cloud engineering
 
Kandroid for nhn_deview_20131013_v5_final
Kandroid for nhn_deview_20131013_v5_finalKandroid for nhn_deview_20131013_v5_final
Kandroid for nhn_deview_20131013_v5_final
 
Android Internals
Android InternalsAndroid Internals
Android Internals
 
Android Internals
Android InternalsAndroid Internals
Android Internals
 
Spring cloud for microservices architecture
Spring cloud for microservices architectureSpring cloud for microservices architecture
Spring cloud for microservices architecture
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
ควบคุมบอร์ดArduinoผ่านระบบandroid
ควบคุมบอร์ดArduinoผ่านระบบandroidควบคุมบอร์ดArduinoผ่านระบบandroid
ควบคุมบอร์ดArduinoผ่านระบบandroid
 
Android Jetpack + Coroutines: To infinity and beyond
Android Jetpack + Coroutines: To infinity and beyondAndroid Jetpack + Coroutines: To infinity and beyond
Android Jetpack + Coroutines: To infinity and beyond
 
Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...Using and Customizing the Android Framework / part 4 of Embedded Android Work...
Using and Customizing the Android Framework / part 4 of Embedded Android Work...
 
The new Netflix API
The new Netflix APIThe new Netflix API
The new Netflix API
 
Build microservice with gRPC in golang
Build microservice with gRPC in golangBuild microservice with gRPC in golang
Build microservice with gRPC in golang
 
OWF12/PAUG Conf Days Android tools for developpeurs, paul marois, design and ...
OWF12/PAUG Conf Days Android tools for developpeurs, paul marois, design and ...OWF12/PAUG Conf Days Android tools for developpeurs, paul marois, design and ...
OWF12/PAUG Conf Days Android tools for developpeurs, paul marois, design and ...
 
Twisted
TwistedTwisted
Twisted
 
Explore Android Internals
Explore Android InternalsExplore Android Internals
Explore Android Internals
 
Android Whats running in background
Android Whats running in backgroundAndroid Whats running in background
Android Whats running in background
 
Android101
Android101Android101
Android101
 
Norikra: SQL Stream Processing In Ruby
Norikra: SQL Stream Processing In RubyNorikra: SQL Stream Processing In Ruby
Norikra: SQL Stream Processing In Ruby
 
ql.io at NodePDX
ql.io at NodePDXql.io at NodePDX
ql.io at NodePDX
 
Monitoring as Code: Getting to Monitoring-Driven Development - DEV314 - re:In...
Monitoring as Code: Getting to Monitoring-Driven Development - DEV314 - re:In...Monitoring as Code: Getting to Monitoring-Driven Development - DEV314 - re:In...
Monitoring as Code: Getting to Monitoring-Driven Development - DEV314 - re:In...
 
[KubeCon EU 2020] containerd Deep Dive
[KubeCon EU 2020] containerd Deep Dive[KubeCon EU 2020] containerd Deep Dive
[KubeCon EU 2020] containerd Deep Dive
 

UA Mobile 2012 (English)

  • 1. Serving your business logically Dmitry Malykhanov DataArt The Android robot is reproduced or modified from work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License.
  • 2. First of all why we need services How is it done service variants Then start execution Expedited delivery receiving your data
  • 3. First of all why exactly we need services
  • 4. Alternatives "Just" Code: Service: ● Thread (pool) ○ return to UI thread ● AsyncTask ○ serialized ○ short lifespan ● Application ? ○ garbage on the heap ○ no IPC
  • 5. Alternatives "Just" Code: Service: ● Thread (pool) ○ return to UI thread ● AsyncTask ○ serialized ○ short lifespan ● Application ? ○ garbage on the heap ○ no IPC
  • 6. Alternatives "Just" Code: Service: ● Thread (pool) ○ return to UI thread ● AsyncTask ○ serialized ○ short lifespan ● Application ? ○ garbage on the heap ○ no IPC
  • 7. Alternatives "Just" Code: Service: ● Thread (pool) ● Thread/Pool/Etc. ○ return to UI thread ○ flexible control ● AsyncTask ● Wake Locks ○ serialized ○ guaranteed CPU ○ short lifespan ● Lifetime ● Application ○ on its own ○ garbage on the heap ○ no IPC
  • 8. Alternatives "Just" Code: Service: ● Thread (pool) ● Thread/Pool/Etc. ○ return to UI thread ○ flexible control ● AsyncTask ● Wake Locks ○ serialized ○ guaranteed CPU ○ short lifespan ● Lifetime ● Application ○ on its own ○ garbage on the heap ○ no IPC
  • 9. Alternatives "Just" Code: Service: ● Thread (pool) ● Thread/Pool/Etc. ○ return to UI thread ○ flexible control ● AsyncTask ● Wake Locks ○ serialized ○ guaranteed CPU ○ short lifespan ● Lifetime ● Application ○ on its own ○ garbage on the heap ○ no IPC
  • 10. What's the price? ● IPC ● Resources ● Security
  • 11. What's the price? ● IPC ● Resources ● SECURITY AndroidManifest.xml: <service ... android:exported="false" />
  • 12. How it is done service kinds and variants
  • 13. Simple service IntentService: ● single thead ● requested enqueued ● clear lifecycle http://goo.gl/TvtbV
  • 14. Cloning simple services Two/three tasks at the same time: <service android:name=".FirstIntentService" /> <service android:name=".SecondIntentService" /> <service android:name=".ThirdIntentService" />
  • 15. Complex services ExecutorService: ● ThreadPoolExecutor ● Scheduled ThreadPoolExecutor http://goo.gl/mwV90
  • 16. Lifecycle: issue IntentService ThreadPoolService ?
  • 17. Lifecycle: solution startId -> ConcurrentLinkedQueue requests: 1, 2, 3, 4, 5 Thread 1 3 4 4 4 idle Thread 2 2 2 5 idle idle Queue 1,2,3,4,5 2,3,4,5 3,4,5 4, 5 5 STOP
  • 19. What and how? switch (cmdId) { case CMD_POLL: poll(); How to expand? break; case CMD_UPLOAD: upload(); break; if ("poll".equals(cmd)) { poll(); } else if ("upload".equals(cmd)) { upload(); }
  • 20. Independence GoF: Command Pattern interface Command { void execute(Context); } 4 http://goo.gl/hwFY9
  • 21. Unique IDs public static final int CMD_POLL = 10; public static final int CMD_UPLOAD = 20; ... Command.class.hashCode() System.identityHashCode()
  • 22. Commands delivery switch (commandId) { case CMD_POLL: return new PollCommand().execute(); case CMD_UPLOAD: return new UploadCommand().execute(); ... abstract class Command implements Parcelable { public abstract void execute(...); }
  • 23. Out of band execution Serialize/prioritize commands, e.g.: Command.isSerial() frameworks/base/core/java/android/os/AsyncTask.java: private static class SerialExecutor implements Executor { ...
  • 25. Wrapping the data ● Entity Bean ● android.os.Bundle
  • 26. Wrapping the data ● Entity Bean YES: type-safe ○ NO: CPU cycles ○ NO: IPC ○ ● android.os.Bundle ○ YES: no type conversion ○ NO: Parcelable only
  • 27. Wrapping the data ● Entity Bean YES: type-safe ○ NO: CPU cycles ○ NO: IPC ○ ● android.os.Bundle ○ YES: no type conversion ○ NO: Parcelable only
  • 28. Universal container public class EntityBean implements Parcelable { ... http://goo.gl/QSFPe
  • 29. Serializable? No way! Serializable - the best of all? Parcelable ^ Parcelable S p 5..10 times e e FASTER! d ^ Serializable
  • 30. One way ticket Delivery transport: ● broadcast Issues: ● IPC ● wakelock ● receiver's lifecycle LocalBroadcastManager http://goo.gl/2h80u
  • 31. Batch them Delivery transport: ● database (provider) Issues: ● delays ● notification "storm" http://goo.gl/ZPoei
  • 32. Messenger bag Delivery transport: ● singleton Issue: ● single process ● memory consumption ● tight coupling http://goo.gl/yfHPn http://goo.gl/5AR9h
  • 33. Courier delivery import android.os.ResultReceiver; private ResultReceiver receiver = new ResultReceiver(handler) { ... } ... new PollCommand(receiver) .start(...); http://goo.gl/rwhw0
  • 34. Zombie-problem Receiver Sender Activity Service Receiver Sender onDestroy Activity Service Receiver Activity Receiver Sender Sender onCreate Activity Service
  • 35. Eternal life Application Receiver Sender Service Activity Application Receiver Sender Service Activity Activity
  • 36. Eternal life: problems Application Receiver Sender ? Service Activity Garbage Collected Application Receiver Sender Service Activity
  • 37. Life without problems Application Buffer Receiver Sender Service Activity
  • 38. Smooth: UI Thread private ResultReceiver receiver = new ResultReceiver(new Handler()) { ... } UI Thread!
  • 39. Smooth: Background private Handler handler = new Handler(handlerThread); private ResultReceiver receiver = new ResultReceiver(handler) { ... onReceive(...) { ... runOnUiThread(...) UI } }
  • 40. Smooth: altogether private ResultReceiver receiverUi = new ResultReceiver(uiThrdHandler) { ... } private ResultReceiver receiverBg = new ResultReceiver(bgThrdHandler) { ... }
  • 41. Best of both worlds join all in one
  • 42. Universal all-in-one service GC AIDL Binder Queue get(id) submit(id, command) Receiver Command Command Service
  • 43. Serving your business logically Dmitry Malykhanov Questions?
  • 44. Serving your business logically The Android robot is reproduced or modified from work created and shared by Google and used according to terms described in the Creative Commons 3.0 Attribution License.