SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

Concurrency Utilities in Java 8
Concurrency Utilities in Java 8Concurrency Utilities in Java 8
Concurrency Utilities in Java 8
Martin Toshev
 

Was ist angesagt? (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
 

Ähnlich wie Android Working in the Background

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
 
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
Utkarsh Mankad
 
UA Mobile 2012 (English)
UA Mobile 2012 (English)UA Mobile 2012 (English)
UA Mobile 2012 (English)
dmalykhanov
 

Ähnlich wie 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
 

Mehr von Vladimir Kotov

Mehr von 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
 

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

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