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