Android Working in the Background

4,129
-1

Published on

Published in: Technology, Education
0 Comments
7 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
4,129
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
7
Embeds 0
No embeds

No notes for slide

Android Working in the Background

  1. 1. Working in the BackgroundVladimir Kotov Working in the Background 1
  2. 2. Android RuntimeVladimir Kotov Working in the Background 2
  3. 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 zygoteVladimir Kotov Working in the Background 3
  4. 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 machineVladimir Kotov Working in the Background 4
  5. 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 spaceVladimir Kotov Working in the Background 5
  6. 6. “Killer” ApplicationVladimir Kotov Working in the Background 6
  7. 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 threadVladimir Kotov Working in the Background 7
  8. 8. Android Single Threading ModelLooper - runs a message loop for a threadMessage - defines a message containing a description and arbitrary data object that can be sent to a HandlerHandler - allows to send and process Message and Runnable objects associated with a threads MessageQueue. Each Handler instance is associated with a single thread and that threads message queue.Vladimir Kotov Working in the Background 8
  9. 9. “Killer” application. Postmortem1) User clicks a button on screen2) UI thread dispatches the clickevent to the widget3) OnClick handler sets its textand posts an invalidate requestto the event queue4) UI thread dequeues therequest and notifies the widgetthat it should redraw itselfVladimir Kotov Working in the Background 9
  10. 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 ResponsiveVladimir Kotov Working in the Background 10
  11. 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. 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. 13. Worker Threads ● Activity.runOnUiThread(Runnable) ● View.post(Runnable) ● View.postDelayed(Runnable, long)Vladimir Kotov Working in the Background 13
  14. 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 yourselfVladimir Kotov Working in the Background 14
  15. 15. AsyncTask in ActionVladimir Kotov Working in the Background 15
  16. 16. Whats Next ...Vladimir Kotov Working in the Background 16
  17. 17. Vladimir Kotov Working in the Background 17
  18. 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 instanceVladimir Kotov Working in the Background 18
  19. 19. AsyncTask ProblemVladimir Kotov Working in the Background 19
  20. 20. Services Broadcast Receivers Intents Activities Services Views Content ProvidersVladimir Kotov Working in the Background 20
  21. 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, etcVladimir Kotov Working in the Background 21
  22. 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 interactionVladimir Kotov Working in the Background 22
  23. 23. NB! ● Service does not run in a separate process ● Service does not create its own thread ● Service runs in the main threadVladimir Kotov Working in the Background 23
  24. 24. Service LifecycleVladimir Kotov Working in the Background 24
  25. 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. 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 dont 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. 27. IntentServiceVladimir Kotov Working in the Background 27
  28. 28. Android Web ServiceVladimir Kotov Working in the Background 28
  29. 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 poolingVladimir Kotov Working in the Background 29
  30. 30. HttpURLConnection ● HttpURLConnection is a general-purpose, lightweight HTTP client suitable for most applicationsVladimir Kotov Working in the Background 30
  31. 31. Apache HttpClient ● Extensible HTTP clients suitable for web browsers. Have large and flexible APIs.Vladimir Kotov Working in the Background 31
  32. 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. 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. 34. JSON Parsing with GSONVladimir Kotov Working in the Background 34
  35. 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. 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 pointVladimir Kotov Working in the Background 36
  37. 37. Sync Purchase Lists ● Task3: Sync service configuration via preferences ● Task4: Export/Import adoption in Purchase list appVladimir Kotov Working in the Background 37

×