SlideShare a Scribd company logo
1 of 37
Working in the Background




Vladimir Kotov     Working in the Background   1
Android Runtime




Vladimir Kotov       Working in the Background   2
Android Runtime
     Zygote spawns VM processes
      ●   Already has core libraries loaded
      ●   When an app is launched, zygote is forked
      ●   Fork core libraries are shared with zygote




Vladimir Kotov                Working in the Background   3
Android Runtime
     By default
      ●   system assigns each application a unique Linux user ID
      ●   every application runs in its own Linux process
      ●   each process has its own virtual machine




Vladimir Kotov                Working in the Background            4
Process v. Thread
   Process
    ●   typically independent
    ●   has considerably more state
        information than thread
    ●   separate address spaces
    ●   interact only through system IPC


   Thread
    ●   subsets of a process
    ●   multiple threads within a process
        share process state, memory, etc
    ●   threads share their address space



Vladimir Kotov                     Working in the Background   5
β€œKiller” Application




Vladimir Kotov         Working in the Background   6
Android Process and Thread
 ●   Android starts a new Linux            ●   System creates a thread of
     process for the application               execution for the application
     with a single thread of                   (β€œmain” / β€œUI” thread) when
     execution                                 application is launched
 ●   Android can shut down a               ●   System does not create a
     process when memory is low,               separate thread for each
     application components                    instance of a component
     running in the process are                 ●   components are
     destroyed
                                                    instantiated in the UI
                                                    thread
                                                ●   system calls (callbacks) to
                                                    components are
                                                    dispatched from UI thread
Vladimir Kotov              Working in the Background                          7
Android Single Threading Model
Looper - runs a message loop for a
  thread

Message - defines a message
  containing a description and
  arbitrary data object that can be
  sent to a Handler

Handler - allows to send and process
  Message and Runnable objects
  associated with a thread's
  MessageQueue. Each Handler
  instance is associated with a single
  thread and that thread's message
  queue.
Vladimir Kotov               Working in the Background   8
β€œKiller” application. Postmortem

1) User clicks a button on screen
2) UI thread dispatches the click
event to the widget
3) OnClick handler sets its text
and posts an invalidate request
to the event queue
4) UI thread dequeues the
request and notifies the widget
that it should redraw itself



Vladimir Kotov             Working in the Background   9
Rules of Thumb
 ●   Do not block the UI thread
      ●   Potentially long running operations (ie. network or
          database operations, expensive calculations, etc.)
          should be done in a child thread


 ●   Do not access the Android UI toolkit from
     outside the UI thread
      ●   Android UI toolkit is not thread-safe and must always
          be manipulated on the UI thread


 ●   Keep your app Responsive

Vladimir Kotov                   Working in the Background        10
Worker Threads
 ●   If you have operations to perform that are not
     instantaneous, you should make sure to do them in
     separate threads ("background" or "worker" threads)




Vladimir Kotov           Working in the Background         11
Worker Threads
 ●   If you have operations to perform that are not
     instantaneous, you should make sure to do them in
     separate threads ("background" or "worker" threads)




Vladimir Kotov           Working in the Background         12
Worker Threads
 ●   Activity.runOnUiThread(Runnable)
 ●   View.post(Runnable)
 ●   View.postDelayed(Runnable, long)




Vladimir Kotov             Working in the Background   13
AsyncTask
 ●   Best practice pattern for moving your time-consuming
     operations onto a background Thread
 ●   Allows to perform asynchronous work on user interface
      ●   performs blocking operations in a worker thread
                 doInBackground()

      ●   publishes the results on the UI thread
                 onPostExecute()

      ●   does not require handling threads and handlers yourself
Vladimir Kotov                Working in the Background        14
AsyncTask in Action




Vladimir Kotov         Working in the Background   15
What's Next ...




Vladimir Kotov      Working in the Background   16
Vladimir Kotov   Working in the Background   17
AsyncTask Problem
    Activity.onRetainNonConfigurationInstance()
      ●   Called by the system, as part of destroying an activity due to
          a configuration change, when it is known that a new instance
          will immediately be created for the new configuration


    Activity.getLastNonConfigurationInstance()
      ●   Retrieve the non-configuration instance data that was
          previously returned by onRetainNonConfigurationInstance().
          This will be available from the initial onCreate and onStart
          calls to the new instance, allowing you to extract any useful
          dynamic state from the previous instance


Vladimir Kotov                 Working in the Background                   18
AsyncTask Problem




Vladimir Kotov        Working in the Background   19
Services
                                Broadcast
                                Receivers

                 Intents                                   Activities




        Services                                         Views


                  Content
                 Providers
Vladimir Kotov               Working in the Background              20
Services
     When a Service Used
 ●   Application need to run
     processes for a long time without
     any intervention from the user, or
     very rare interventions
 ●   These background processes
     need to keep running even when
     the phone is being used for other
     activities / tasks
 ●   Network transactions, play
     music, perform file I/O, etc

Vladimir Kotov             Working in the Background   21
Services and Notifications
 ●   Service does not implement any
     user interface
 ●   Service β€œnotifies” the user through
     the notification (such as status bar
     notification)
 ●   Service can give a user interface for
     binding to the service or viewing the
     status of the service or any other
     similar interaction




Vladimir Kotov             Working in the Background   22
NB!

 ●   Service does not run in a separate process
 ●   Service does not create its own thread
 ●   Service runs in the main thread




Vladimir Kotov        Working in the Background   23
Service Lifecycle




Vladimir Kotov       Working in the Background   24
Starting a Service
 ●   Context.startService()
      ●   Retrieve the service (creating it and calling its onCreate()
          method if needed)
      ●   Call onStartCommand(Intent, int, int) method of the service
          with the arguments supplied

 ●   The service will continue running until
     Context.stopService() or stopSelf() is called


 ●   <service android:name="com.example.service.MyService"/>

Vladimir Kotov                Working in the Background                  25
IntentService
 Uses a worker thread to handle            ●
                                               Creates a default worker
   all start requests, one at a                thread that executes all
   time. The best option if you                intents delivered to
   don't require that your                     onStartCommand()
   service handle multiple
   requests simultaneously.
                                           ●
                                               Creates a work queue that
                                               passes one intent at a time
 β€œSet it and forget it” – places
                                               to your onHandleIntent()
   request on Service Queue,               ●
                                               Stops the service after all
   which handles action (and                   start requests have been
   β€œmay take as long as                        handled
   necessary”)

Vladimir Kotov              Working in the Background                        26
IntentService




Vladimir Kotov     Working in the Background   27
Android Web Service




Vladimir Kotov         Working in the Background   28
Android and HTTP
 ●   Connecting to an Internet Resource
          <uses-permission
          android:name=”android.permission.INTERNET”/>
 ●   Android includes two HTTP clients:
      ●   HttpURLConnection
      ●   Apache HTTP Client
 ●   Support HTTPS, streaming uploads and downloads,
     configurable timeouts, IPv6 and connection pooling



Vladimir Kotov            Working in the Background       29
HttpURLConnection
 ●   HttpURLConnection is a general-purpose, lightweight
     HTTP client suitable for most applications




Vladimir Kotov           Working in the Background         30
Apache HttpClient
 ●   Extensible HTTP clients suitable for web browsers. Have
     large and flexible APIs.




Vladimir Kotov           Working in the Background             31
JSON Parsing with JSONObject
 ●   JSON (JavaScript Object Notation), is a text-based open standard
     designed for human-readable data interchange. It is derived from the
     JavaScript scripting language for representing simple data structures
     and associative arrays, called objects.


 ●   Built-in JSONTokener / JSONObject                            {

     JSONTokener jsonTokener = new JSONTokener(response);         "My Purchase List":[

     JSONObject object = (JSONObject) jsonTokener.nextValue();    {"name":"Bread","quantity":"11"}],
     object = object.getJSONObject("patient");                    "Mom Purchase List":[
     patientName = object.getString("name");                      {"name":"Tomato","quantity":"2"}]
     patientSurname = object.getString("surname");                }




Vladimir Kotov                        Working in the Background                               32
JSON Parsing with GSON
 ●   Gson is a Java library that can be used to convert Java
     Objects into their JSON representation. It can also be used
     to convert a JSON string to an equivalent Java object
      ●   Simple toJson() and fromJson() methods to convert
          Java objects to JSON and vice-versa
      ●   Extensive support of Java Generics
      ●   Allow custom representations for objects
      ●   Support arbitrarily complex objects (with deep
          inheritance hierarchies and extensive use of generic
          types)


Vladimir Kotov              Working in the Background            33
JSON Parsing with GSON




Vladimir Kotov      Working in the Background   34
Workshop
 ●   Purchase list synchronization                     Example
                                                       http://kotov.lv/JavaguryServices/purchases/
      ●   Web-service (REST)                           vladkoto
            –    https://github.com/rk13/java
                 guru-services
                                                       {
            –    http://kotov.lv/JavaguryServ
                                                        "My Purchase List":[
                 ices/purchases/
                                                       {"name":"Bread","quantity":"11"},
                                                       {"name":"Jameson Wiskey","quantity":"1"}],
      ●   API
                                                        "Mom Purchase List":[
            –    http://kotov.lv/JavaguryServ
                 ices/purchases/{TOKEN}                {"name":"Cranberry","quantity":"1kg"},

            –    GET / POST                            {"name":"Tomato","quantity":"2"}]
                                                       }



Vladimir Kotov                       Working in the Background                                  35
Sync Purchase Lists
 ●   Task1: Import purchase lists
      ●   Use AsyncTask
      ●   Load json from service
      ●   Convert and display
      ●   HttpTask.java for starting point

 ●   Task2: Export purchase lists
      ●   Use IntentService
      ●   Convert and push json to server
      ●   ExportService.java for starting point
Vladimir Kotov                Working in the Background   36
Sync Purchase Lists
 ●   Task3: Sync service configuration via preferences


 ●   Task4: Export/Import adoption in Purchase list app




Vladimir Kotov             Working in the Background      37

More Related Content

What's hot

Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 ThreadingDiego Grancini
Β 
09 gui 13
09 gui 1309 gui 13
09 gui 13Niit Care
Β 
10 ways to improve your Android app performance
10 ways to improve your Android app performance10 ways to improve your Android app performance
10 ways to improve your Android app performanceBoris Farber
Β 
Multithreading in Android
Multithreading in AndroidMultithreading in Android
Multithreading in Androidcoolmirza143
Β 
Javascript internals
Javascript internalsJavascript internals
Javascript internalsNir Noy
Β 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate
Β 
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS EngineZongXian Shen
Β 
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckCut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckTheo Jungeblut
Β 
Toward dynamic analysis of obfuscated android malware
Toward dynamic analysis of obfuscated android malwareToward dynamic analysis of obfuscated android malware
Toward dynamic analysis of obfuscated android malwareZongXian Shen
Β 
Recon2016 shooting the_osx_el_capitan_kernel_like_a_sniper_chen_he
Recon2016 shooting the_osx_el_capitan_kernel_like_a_sniper_chen_heRecon2016 shooting the_osx_el_capitan_kernel_like_a_sniper_chen_he
Recon2016 shooting the_osx_el_capitan_kernel_like_a_sniper_chen_heLiang Chen
Β 
Deploying JHipster Microservices
Deploying JHipster MicroservicesDeploying JHipster Microservices
Deploying JHipster MicroservicesJoe Kutner
Β 
Jenkins 101: Continuos Integration with Jenkins
Jenkins 101: Continuos Integration with JenkinsJenkins 101: Continuos Integration with Jenkins
Jenkins 101: Continuos Integration with JenkinsAll Things Open
Β 
Singleton Object Management
Singleton Object ManagementSingleton Object Management
Singleton Object Managementppd1961
Β 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloadedcbeyls
Β 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Martin Toshev
Β 
Qt test framework
Qt test frameworkQt test framework
Qt test frameworkICS
Β 
Inside the Android application framework - Google I/O 2009
Inside the Android application framework - Google I/O 2009Inside the Android application framework - Google I/O 2009
Inside the Android application framework - Google I/O 2009Viswanath J
Β 
OpenDaylight Developer Experience 2.0
 OpenDaylight Developer Experience 2.0 OpenDaylight Developer Experience 2.0
OpenDaylight Developer Experience 2.0Michael Vorburger
Β 
Unit Test Android Without Going Bald
Unit Test Android Without Going BaldUnit Test Android Without Going Bald
Unit Test Android Without Going BaldDavid Carver
Β 

What's hot (20)

Android App Development - 07 Threading
Android App Development - 07 ThreadingAndroid App Development - 07 Threading
Android App Development - 07 Threading
Β 
09 gui 13
09 gui 1309 gui 13
09 gui 13
Β 
10 ways to improve your Android app performance
10 ways to improve your Android app performance10 ways to improve your Android app performance
10 ways to improve your Android app performance
Β 
Multithreading in Android
Multithreading in AndroidMultithreading in Android
Multithreading in Android
Β 
Javascript internals
Javascript internalsJavascript internals
Javascript internals
Β 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect Guide
Β 
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
(COSCUP 2015) A Beginner's Journey to Mozilla SpiderMonkey JS Engine
Β 
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group OsnabrueckCut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Β 
Toward dynamic analysis of obfuscated android malware
Toward dynamic analysis of obfuscated android malwareToward dynamic analysis of obfuscated android malware
Toward dynamic analysis of obfuscated android malware
Β 
Recon2016 shooting the_osx_el_capitan_kernel_like_a_sniper_chen_he
Recon2016 shooting the_osx_el_capitan_kernel_like_a_sniper_chen_heRecon2016 shooting the_osx_el_capitan_kernel_like_a_sniper_chen_he
Recon2016 shooting the_osx_el_capitan_kernel_like_a_sniper_chen_he
Β 
Deploying JHipster Microservices
Deploying JHipster MicroservicesDeploying JHipster Microservices
Deploying JHipster Microservices
Β 
Jenkins 101: Continuos Integration with Jenkins
Jenkins 101: Continuos Integration with JenkinsJenkins 101: Continuos Integration with Jenkins
Jenkins 101: Continuos Integration with Jenkins
Β 
Singleton Object Management
Singleton Object ManagementSingleton Object Management
Singleton Object Management
Β 
Android Loaders : Reloaded
Android Loaders : ReloadedAndroid Loaders : Reloaded
Android Loaders : Reloaded
Β 
Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
Β 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
Β 
Inside the Android application framework - Google I/O 2009
Inside the Android application framework - Google I/O 2009Inside the Android application framework - Google I/O 2009
Inside the Android application framework - Google I/O 2009
Β 
OpenDaylight Developer Experience 2.0
 OpenDaylight Developer Experience 2.0 OpenDaylight Developer Experience 2.0
OpenDaylight Developer Experience 2.0
Β 
Unit Test Android Without Going Bald
Unit Test Android Without Going BaldUnit Test Android Without Going Bald
Unit Test Android Without Going Bald
Β 
Introduction to NodeJS
Introduction to NodeJSIntroduction to NodeJS
Introduction to NodeJS
Β 

Similar to Android Working in the Background

Vm final
Vm finalVm final
Vm finalChiao Fu
Β 
Android Internals at Linaro Connect Asia 2013
Android Internals at Linaro Connect Asia 2013Android Internals at Linaro Connect Asia 2013
Android Internals at Linaro Connect Asia 2013Opersys inc.
Β 
[iOS] Multiple Background Threads
[iOS] Multiple Background Threads[iOS] Multiple Background Threads
[iOS] Multiple Background ThreadsNikmesoft Ltd
Β 
[Android] Multiple Background Threads
[Android] Multiple Background Threads[Android] Multiple Background Threads
[Android] Multiple Background ThreadsNikmesoft Ltd
Β 
Mateusz 'j00ru' Jurczyk - Windows Kernel Trap Handler and NTVDM Vulnerabiliti...
Mateusz 'j00ru' Jurczyk - Windows Kernel Trap Handler and NTVDM Vulnerabiliti...Mateusz 'j00ru' Jurczyk - Windows Kernel Trap Handler and NTVDM Vulnerabiliti...
Mateusz 'j00ru' Jurczyk - Windows Kernel Trap Handler and NTVDM Vulnerabiliti...DefconRussia
Β 
Leveraging Android's Linux Heritage at AnDevCon3
Leveraging Android's Linux Heritage at AnDevCon3Leveraging Android's Linux Heritage at AnDevCon3
Leveraging Android's Linux Heritage at AnDevCon3Opersys inc.
Β 
Leveraging Android's Linux Heritage
Leveraging Android's Linux HeritageLeveraging Android's Linux Heritage
Leveraging Android's Linux HeritageOpersys inc.
Β 
Threads handlers and async task, widgets - day8
Threads   handlers and async task, widgets - day8Threads   handlers and async task, widgets - day8
Threads handlers and async task, widgets - day8Utkarsh Mankad
Β 
Android Whats running in background
Android Whats running in backgroundAndroid Whats running in background
Android Whats running in backgroundNaval Kishore Barthwal
Β 
Cloud Security with LibVMI
Cloud Security with LibVMICloud Security with LibVMI
Cloud Security with LibVMITamas K Lengyel
Β 
Leveraging Android's Linux Heritage at ELC-E 2011
Leveraging Android's Linux Heritage at ELC-E 2011Leveraging Android's Linux Heritage at ELC-E 2011
Leveraging Android's Linux Heritage at ELC-E 2011Opersys inc.
Β 
Singularity: The Inner Workings of Securely Running User Containers on HPC Sy...
Singularity: The Inner Workings of Securely Running User Containers on HPC Sy...Singularity: The Inner Workings of Securely Running User Containers on HPC Sy...
Singularity: The Inner Workings of Securely Running User Containers on HPC Sy...inside-BigData.com
Β 
Workshop su Android Kernel Hacking
Workshop su Android Kernel HackingWorkshop su Android Kernel Hacking
Workshop su Android Kernel HackingDeveler S.r.l.
Β 
UA Mobile 2012 (English)
UA Mobile 2012 (English)UA Mobile 2012 (English)
UA Mobile 2012 (English)dmalykhanov
Β 
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...DroidConTLV
Β 
Android Internals
Android InternalsAndroid Internals
Android InternalsOpersys inc.
Β 
CNIT 126: 10: Kernel Debugging with WinDbg
CNIT 126: 10: Kernel Debugging with WinDbgCNIT 126: 10: Kernel Debugging with WinDbg
CNIT 126: 10: Kernel Debugging with WinDbgSam Bowne
Β 

Similar to Android Working in the Background (20)

Vm final
Vm finalVm final
Vm final
Β 
Android Internals at Linaro Connect Asia 2013
Android Internals at Linaro Connect Asia 2013Android Internals at Linaro Connect Asia 2013
Android Internals at Linaro Connect Asia 2013
Β 
[iOS] Multiple Background Threads
[iOS] Multiple Background Threads[iOS] Multiple Background Threads
[iOS] Multiple Background Threads
Β 
[Android] Multiple Background Threads
[Android] Multiple Background Threads[Android] Multiple Background Threads
[Android] Multiple Background Threads
Β 
Mateusz 'j00ru' Jurczyk - Windows Kernel Trap Handler and NTVDM Vulnerabiliti...
Mateusz 'j00ru' Jurczyk - Windows Kernel Trap Handler and NTVDM Vulnerabiliti...Mateusz 'j00ru' Jurczyk - Windows Kernel Trap Handler and NTVDM Vulnerabiliti...
Mateusz 'j00ru' Jurczyk - Windows Kernel Trap Handler and NTVDM Vulnerabiliti...
Β 
Explore Android Internals
Explore Android InternalsExplore Android Internals
Explore Android Internals
Β 
Leveraging Android's Linux Heritage at AnDevCon3
Leveraging Android's Linux Heritage at AnDevCon3Leveraging Android's Linux Heritage at AnDevCon3
Leveraging Android's Linux Heritage at AnDevCon3
Β 
Leveraging Android's Linux Heritage
Leveraging Android's Linux HeritageLeveraging Android's Linux Heritage
Leveraging Android's Linux Heritage
Β 
Threads handlers and async task, widgets - day8
Threads   handlers and async task, widgets - day8Threads   handlers and async task, widgets - day8
Threads handlers and async task, widgets - day8
Β 
Android Whats running in background
Android Whats running in backgroundAndroid Whats running in background
Android Whats running in background
Β 
Cloud Security with LibVMI
Cloud Security with LibVMICloud Security with LibVMI
Cloud Security with LibVMI
Β 
Leveraging Android's Linux Heritage at ELC-E 2011
Leveraging Android's Linux Heritage at ELC-E 2011Leveraging Android's Linux Heritage at ELC-E 2011
Leveraging Android's Linux Heritage at ELC-E 2011
Β 
Android101
Android101Android101
Android101
Β 
Singularity: The Inner Workings of Securely Running User Containers on HPC Sy...
Singularity: The Inner Workings of Securely Running User Containers on HPC Sy...Singularity: The Inner Workings of Securely Running User Containers on HPC Sy...
Singularity: The Inner Workings of Securely Running User Containers on HPC Sy...
Β 
Workshop su Android Kernel Hacking
Workshop su Android Kernel HackingWorkshop su Android Kernel Hacking
Workshop su Android Kernel Hacking
Β 
Android Attacks
Android AttacksAndroid Attacks
Android Attacks
Β 
UA Mobile 2012 (English)
UA Mobile 2012 (English)UA Mobile 2012 (English)
UA Mobile 2012 (English)
Β 
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
Think Async: Understanding the Complexity of Multithreading - Avi Kabizon & A...
Β 
Android Internals
Android InternalsAndroid Internals
Android Internals
Β 
CNIT 126: 10: Kernel Debugging with WinDbg
CNIT 126: 10: Kernel Debugging with WinDbgCNIT 126: 10: Kernel Debugging with WinDbg
CNIT 126: 10: Kernel Debugging with WinDbg
Β 

More from Vladimir Kotov

e-Business - Mobile development trends
e-Business - Mobile development trendse-Business - Mobile development trends
e-Business - Mobile development trendsVladimir Kotov
Β 
e-Business - SE trends
e-Business - SE trendse-Business - SE trends
e-Business - SE trendsVladimir Kotov
Β 
Android Internals and Toolchain
Android Internals and ToolchainAndroid Internals and Toolchain
Android Internals and ToolchainVladimir Kotov
Β 

More from Vladimir Kotov (8)

e-Business - Mobile development trends
e-Business - Mobile development trendse-Business - Mobile development trends
e-Business - Mobile development trends
Β 
e-Business - SE trends
e-Business - SE trendse-Business - SE trends
e-Business - SE trends
Β 
LDP lecture 2
LDP lecture 2LDP lecture 2
LDP lecture 2
Β 
LDP lecture 1
LDP lecture 1LDP lecture 1
LDP lecture 1
Β 
Android Internals and Toolchain
Android Internals and ToolchainAndroid Internals and Toolchain
Android Internals and Toolchain
Β 
LDP lecture 5
LDP lecture 5LDP lecture 5
LDP lecture 5
Β 
LDP lecture 4
LDP lecture 4LDP lecture 4
LDP lecture 4
Β 
LDP lecture 3
LDP lecture 3LDP lecture 3
LDP lecture 3
Β 

Recently uploaded

Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
Β 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
Β 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel AraΓΊjo
Β 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
Β 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
Β 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
Β 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
Β 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
Β 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
Β 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
Β 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
Β 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
Β 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
Β 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
Β 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
Β 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
Β 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
Β 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
Β 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
Β 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
Β 

Recently uploaded (20)

Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
Β 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
Β 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Β 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Β 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
Β 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
Β 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
Β 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
Β 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Β 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Β 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Β 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
Β 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Β 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
Β 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Β 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Β 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
Β 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
Β 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
Β 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Β 

Android Working in the Background

  • 1. Working in the Background Vladimir Kotov Working in the Background 1
  • 2. Android Runtime Vladimir Kotov Working in the Background 2
  • 3. Android Runtime Zygote spawns VM processes ● Already has core libraries loaded ● When an app is launched, zygote is forked ● Fork core libraries are shared with zygote Vladimir Kotov Working in the Background 3
  • 4. Android Runtime By default ● system assigns each application a unique Linux user ID ● every application runs in its own Linux process ● each process has its own virtual machine Vladimir Kotov Working in the Background 4
  • 5. Process v. Thread Process ● typically independent ● has considerably more state information than thread ● separate address spaces ● interact only through system IPC Thread ● subsets of a process ● multiple threads within a process share process state, memory, etc ● threads share their address space Vladimir Kotov Working in the Background 5
  • 6. β€œKiller” Application Vladimir Kotov Working in the Background 6
  • 7. Android Process and Thread ● Android starts a new Linux ● System creates a thread of process for the application execution for the application with a single thread of (β€œmain” / β€œUI” thread) when execution application is launched ● Android can shut down a ● System does not create a process when memory is low, separate thread for each application components instance of a component running in the process are ● components are destroyed instantiated in the UI thread ● system calls (callbacks) to components are dispatched from UI thread Vladimir Kotov Working in the Background 7
  • 8. Android Single Threading Model Looper - runs a message loop for a thread Message - defines a message containing a description and arbitrary data object that can be sent to a Handler Handler - allows to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. Vladimir Kotov Working in the Background 8
  • 9. β€œKiller” application. Postmortem 1) User clicks a button on screen 2) UI thread dispatches the click event to the widget 3) OnClick handler sets its text and posts an invalidate request to the event queue 4) UI thread dequeues the request and notifies the widget that it should redraw itself Vladimir Kotov Working in the Background 9
  • 10. Rules of Thumb ● Do not block the UI thread ● Potentially long running operations (ie. network or database operations, expensive calculations, etc.) should be done in a child thread ● Do not access the Android UI toolkit from outside the UI thread ● Android UI toolkit is not thread-safe and must always be manipulated on the UI thread ● Keep your app Responsive Vladimir Kotov Working in the Background 10
  • 11. Worker Threads ● If you have operations to perform that are not instantaneous, you should make sure to do them in separate threads ("background" or "worker" threads) Vladimir Kotov Working in the Background 11
  • 12. Worker Threads ● If you have operations to perform that are not instantaneous, you should make sure to do them in separate threads ("background" or "worker" threads) Vladimir Kotov Working in the Background 12
  • 13. Worker Threads ● Activity.runOnUiThread(Runnable) ● View.post(Runnable) ● View.postDelayed(Runnable, long) Vladimir Kotov Working in the Background 13
  • 14. AsyncTask ● Best practice pattern for moving your time-consuming operations onto a background Thread ● Allows to perform asynchronous work on user interface ● performs blocking operations in a worker thread doInBackground() ● publishes the results on the UI thread onPostExecute() ● does not require handling threads and handlers yourself Vladimir Kotov Working in the Background 14
  • 15. AsyncTask in Action Vladimir Kotov Working in the Background 15
  • 16. What's Next ... Vladimir Kotov Working in the Background 16
  • 17. Vladimir Kotov Working in the Background 17
  • 18. AsyncTask Problem Activity.onRetainNonConfigurationInstance() ● Called by the system, as part of destroying an activity due to a configuration change, when it is known that a new instance will immediately be created for the new configuration Activity.getLastNonConfigurationInstance() ● Retrieve the non-configuration instance data that was previously returned by onRetainNonConfigurationInstance(). This will be available from the initial onCreate and onStart calls to the new instance, allowing you to extract any useful dynamic state from the previous instance Vladimir Kotov Working in the Background 18
  • 19. AsyncTask Problem Vladimir Kotov Working in the Background 19
  • 20. Services Broadcast Receivers Intents Activities Services Views Content Providers Vladimir Kotov Working in the Background 20
  • 21. Services When a Service Used ● Application need to run processes for a long time without any intervention from the user, or very rare interventions ● These background processes need to keep running even when the phone is being used for other activities / tasks ● Network transactions, play music, perform file I/O, etc Vladimir Kotov Working in the Background 21
  • 22. Services and Notifications ● Service does not implement any user interface ● Service β€œnotifies” the user through the notification (such as status bar notification) ● Service can give a user interface for binding to the service or viewing the status of the service or any other similar interaction Vladimir Kotov Working in the Background 22
  • 23. NB! ● Service does not run in a separate process ● Service does not create its own thread ● Service runs in the main thread Vladimir Kotov Working in the Background 23
  • 24. Service Lifecycle Vladimir Kotov Working in the Background 24
  • 25. Starting a Service ● Context.startService() ● Retrieve the service (creating it and calling its onCreate() method if needed) ● Call onStartCommand(Intent, int, int) method of the service with the arguments supplied ● The service will continue running until Context.stopService() or stopSelf() is called ● <service android:name="com.example.service.MyService"/> Vladimir Kotov Working in the Background 25
  • 26. IntentService Uses a worker thread to handle ● Creates a default worker all start requests, one at a thread that executes all time. The best option if you intents delivered to don't require that your onStartCommand() service handle multiple requests simultaneously. ● Creates a work queue that passes one intent at a time β€œSet it and forget it” – places to your onHandleIntent() request on Service Queue, ● Stops the service after all which handles action (and start requests have been β€œmay take as long as handled necessary”) Vladimir Kotov Working in the Background 26
  • 27. IntentService Vladimir Kotov Working in the Background 27
  • 28. Android Web Service Vladimir Kotov Working in the Background 28
  • 29. Android and HTTP ● Connecting to an Internet Resource <uses-permission android:name=”android.permission.INTERNET”/> ● Android includes two HTTP clients: ● HttpURLConnection ● Apache HTTP Client ● Support HTTPS, streaming uploads and downloads, configurable timeouts, IPv6 and connection pooling Vladimir Kotov Working in the Background 29
  • 30. HttpURLConnection ● HttpURLConnection is a general-purpose, lightweight HTTP client suitable for most applications Vladimir Kotov Working in the Background 30
  • 31. Apache HttpClient ● Extensible HTTP clients suitable for web browsers. Have large and flexible APIs. Vladimir Kotov Working in the Background 31
  • 32. JSON Parsing with JSONObject ● JSON (JavaScript Object Notation), is a text-based open standard designed for human-readable data interchange. It is derived from the JavaScript scripting language for representing simple data structures and associative arrays, called objects. ● Built-in JSONTokener / JSONObject { JSONTokener jsonTokener = new JSONTokener(response); "My Purchase List":[ JSONObject object = (JSONObject) jsonTokener.nextValue(); {"name":"Bread","quantity":"11"}], object = object.getJSONObject("patient"); "Mom Purchase List":[ patientName = object.getString("name"); {"name":"Tomato","quantity":"2"}] patientSurname = object.getString("surname"); } Vladimir Kotov Working in the Background 32
  • 33. JSON Parsing with GSON ● Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object ● Simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa ● Extensive support of Java Generics ● Allow custom representations for objects ● Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic types) Vladimir Kotov Working in the Background 33
  • 34. JSON Parsing with GSON Vladimir Kotov Working in the Background 34
  • 35. Workshop ● Purchase list synchronization Example http://kotov.lv/JavaguryServices/purchases/ ● Web-service (REST) vladkoto – https://github.com/rk13/java guru-services { – http://kotov.lv/JavaguryServ "My Purchase List":[ ices/purchases/ {"name":"Bread","quantity":"11"}, {"name":"Jameson Wiskey","quantity":"1"}], ● API "Mom Purchase List":[ – http://kotov.lv/JavaguryServ ices/purchases/{TOKEN} {"name":"Cranberry","quantity":"1kg"}, – GET / POST {"name":"Tomato","quantity":"2"}] } Vladimir Kotov Working in the Background 35
  • 36. Sync Purchase Lists ● Task1: Import purchase lists ● Use AsyncTask ● Load json from service ● Convert and display ● HttpTask.java for starting point ● Task2: Export purchase lists ● Use IntentService ● Convert and push json to server ● ExportService.java for starting point Vladimir Kotov Working in the Background 36
  • 37. Sync Purchase Lists ● Task3: Sync service configuration via preferences ● Task4: Export/Import adoption in Purchase list app Vladimir Kotov Working in the Background 37