asynchronous techniques //vovanhai.files.wordpress.com/2016/03/5-1... · 3/5/2016 · 23/03/2016 1...
TRANSCRIPT
23/03/2016
1
Android programming course
By Võ Văn Hải
Faculty of Information Technologies
Asynchronous Techniques
Session objectives
• Introduction
• Asynchronous Techniques
o Thread
o Executor
o HandlerThread
o AsyncTask
o Service & IntentService
o AsyncQueryHandler
o Loader
2
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
2
Introduction
3
Lifecycles
Activity Service
BroadcastReceiver
ContentProvider
Android Components
Java Objects
BroadcastReceiver
Activity Service
ContentProvider
LinuxProcess
Threads
BG
BG
BG
UI
4
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
3
ProcessProcess
ApplicationStart
ApplicationEnd
LinuxProcess
Native Thread Lifecycle
UI
BG
Time
5
Example: Activity Lifecycle
Time
ActivityComponent
onCreate() onDestroy() onCreate() onDestroy()
ActivityObject
new() GC
ActivityObject
new() GC
6
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
4
Example: Activity Lifecycle
Time
ActivityComponent
onCreate() onDestroy() onCreate() onDestroy()
ActivityObject
new()
ActivityObject
new()
Start
BG
Reference
7
Example: Activity Lifecycle
Time
ActivityComponent
onCreate() onDestroy() onCreate() onDestroy()
ActivityObject
new()
ActivityObject
new()
Start
BG
Reference
8
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
5
Background Threads
• A thread is a GC root
• Implement cancellation policy for your background threads!
9
Use Cases
Get off the UI thread
early!
Get off the UI thread
early!
Do long running
task
Do long running
task
Get off the UI thread
early!
Get off the UI thread
early!
Report result or
update UI
Report result or
update UI
Do long running
task
Do long running
task
UIThread
BGThread
UIThread
BGThread
10
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
6
Asynchronous Techniques
• Thread
• Executor
• HandlerThread
• AsyncTask
• Service
• IntentService
• AsyncQueryHandler
• Loader
11
ThreadPlain old Java Thread
12
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
7
Creating Tasks and Threads (1)
• Tasks are objects. To create tasks, you have to first define a class
for tasks. A task class must implement the Runnable interface
• You need to implement run method to tell the system how your
thread is going to run
13
Creating Tasks and Threads (2)
14
Or you can use Callable<V> to improve some problems
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
8
Thread - Example
15
Dis-advantages and using
• Pitfalls
o Non-retained threads
o Missing cancellation policy (runnable)
o Starting over and over again
• Good Use Cases
o One-shot tasks
• Post messages to the UI thread at end.
16
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
9
ExecutorPowerful task execution framework.
17
Executor and ExecutorService
18
ExecutorExecutor
ExecutorService
ExecutorService
ThreadPoolExecutor
ThreadPoolExecutor
Task submission:
executorService.submit(MyTask);executorService.invokeAll(Collection<Tasks>);executorService.invokeAny(Collection<Tasks>);
Lifecycle management:
executorService.shutdown();executorService.shutdownNow();
Lifecycle observation:
executorService.isShutdown();executorService.isTerminated();executorService.awaitTermination();
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
10
Task / Execution Environment
19
Task:Independent unit of work executed anywhere
Runnablerun()
Runnablerun()
Callablecall()
Callablecall()
Execution Environment:
Technique used to execute the task
Executorexecute(Runnable)
Executorexecute(Runnable)
Future future = executorService.submit(Callable);
FutureisDone()
isCancelled()cancel()
FutureisDone()
isCancelled()cancel()
Task manager/observer:
Thread Pools
20
Fixed Thread Pool Executors.newFixedThreadPool(3)
Cached Thread Pool Executors.newCachedThreadPool()
Single Thread Pool Executors.newSingleThreadExecutor()
Custom Thread Pool new ThreadPoolExecutor(corePoolSize, maximumPoolSize, aliveTime, unit, workQueue)
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
11
Dis-advantages and using
• Pitfalls
o Lost thread safety when switching from sequential to
concurrent execution
• Good Use Cases
o Execute tasks concurrently
• Multiple Http requests
• Concurrent image processing
• Use cases gaining performance from concurrent execution.
o Lifecycle management and observation of task execution.
o Maximum platform utilization
21
Handler Class
22
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
12
t = new HandlerThread("BgThread");t.start();
1
Handler h = new Handler(t.getLooper()) {@Overridepublic void handleMessage(Message msg) {
//Process message}
};
2
Handler Class
• Inherits from Thread and encapsulates a Looper-object.
• Thread with a message queue and processing loop.
• Handles both Message and Runnable.
23
HandlerThread
Create and Start
Add Process
Message Queue
1
23
h.sendEmptyMessage(42);3
Looper and Handler
24
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
13
Handler
• Runnable/Message submission:
o post(Runnable);
o postDelayed(Runnable);
o postAtTime(Runnable)
o postAtFrontOfQueue(Runnable);
o sendMessage(Message);
o sendMessageDelayed(Message);
o sendMessageAtTime(Message);
o sendMessageAtFrontOfQueue(Message);
• Runnable/Message removal:
o removeCallbacks(Runnable);
o removeMessages(Message)
25
Using sendMessage
26
Main Thread
Background Thread
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
14
Example – using messgae
27
Using post
28
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
15
Good Use Cases
• Keep a thread alive
• Sequential execution of messages
• Avoid concurrent execution on multiple button clicks
• State machine
• Detailed control of message processing.
29
AsyncTask Class
30
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
16
AsyncTask Class
• AsyncTask enables proper and easy use of the UI thread. This
class allows to perform background operations and publish
results on the UI thread without having to manipulate threads
and/or handlers.
• AsyncTask is designed to be a helper class around Thread and
Handler and does not constitute a generic threading
framework.
• An asynchronous task is defined by a computation that runs on
a background thread and whose result is published on the UI
thread.
31
How it works
32
onCancelled()4b4b
UIThread
BGThread
new AsyncTask.execute()1
onPreExecute()2
3doInBackground()
onPostExecute()4a AsyncTask.cancel()
onProgressUpdate()
publishProgress()
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
17
AsyncTask class
AsyncTask's generic types
1. Params, The type of the parameters sent to the task upon execution.
2.Progress The type of the progress units published during the background computation.
3.Result The type of the result of the background computation.33
Example
34
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
18
Service
35
Services
• A Service is an application component that can perform long-
running operations in the background and does not provide a user
interface.
• Another application component can start a service and it will
continue to run in the background even if the user switches to
another application.
• Additionally, a component can bind to a service to interact with
it and even perform interprocess communication (IPC).
36
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
19
Services’s states
State Description
Started
A service is started when an application component, such asan activity, starts it by calling startService(). Oncestarted, a service can run in the background indefinitely,even if the component that started it is destroyed.
Bound
A service is bound when an application component binds toit by calling bindService(). A bound service offers a client-server interface that allows components to interact withthe service, send requests, get results, and even do soacross processes with interprocess communication (IPC).
37
Service lifecycle
38
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
20
Service’s call-back methods
Callback Description
onStartCommand()
The system calls this method when another component, such asan activity, requests that the service be started, by callingstartService().
onBind()The system calls this method when another component wants tobind with the service by calling bindService().
onUnbind()The system calls this method when all clients have disconnectedfrom a particular interface published by the service.
onRebind()The system calls this method when new clients have connectedto the service, after it had previously been notified that all haddisconnected in its onUnbind(Intent).
onCreate()The system calls this method when the service is first createdusing onStartCommand() or onBind().
onDestroy()The system calls this method when the service is no longer usedand is being destroyed.
39
Creating Service
There are two classes you can extend to create a started service
• Service
o This is the base class for all services. When you extend this class, it's
important that you create a new thread in which to do all the service's
work, because the service uses your application's main thread, by default,
which could slow the performance of any activity your application is
running.
• IntentService
o This is a subclass of Service that uses a worker thread to handle all start
requests, one at a time. This is the best option if you don't require that
your service handle multiple requests simultaneously. All you need to do is
implement onHandleIntent(), which receives the intent for each start
request so you can do the background work.
40
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
21
Creating ServiceExtends the IntentService class
• Creates a default worker thread that executes all intents delivered
to onStartCommand() separate from your application's main thread.
• Creates a work queue that passes one intent at a time to your
onHandleIntent() implementation, so you never have to worry about
multi-threading.
• Stops the service after all start requests have been handled, so you
never have to call stopSelf().
• Provides default implementation of onBind() that returns null.
• Provides a default implementation of onStartCommand() that sends
the intent to the work queue and then to your onHandleIntent()
implementation.
41
42
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
22
Creating ServiceExtends the Service class
If you require your service to perform multi-threading (instead of
processing start requests through a work queue), then you can
extend the Service class to handle each intent.
43
44
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
23
• Define your service in AndroidManifest.xml file
45
Service restart behavior
• In its onStartCommand() method call, the service returns an int which
defines its restart behavior in case the service gets terminated by the
Android platform. You can use the constants, the most common options are
described by the following table.
Option Description
Service.START_STICKY
Service is restarted if it gets terminated. Intent datapassed to the onStartCommand method is null. Used forservices which manages their own state and do not dependon the Intent data.
Service.START_NOT_STICKY
Service is not restarted. Used for services which areperiodically triggered anyway. The service is onlyrestarted if the runtime has pending startService() callssince the service termination.
Service.START_REDELIVER_INTENTSimilar to Service.START_STICKY but the original Intentis re-delivered to the onStartCommand method.
You can check if the service was restarted via the Intent.getFlags() method. 46
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
24
Running a service in its own process
• You can also specify that your Service runs in a separate process via
the android:process=":process_description" attribute.
• Running a service in its own process will not block the application in case
the service performs long running operations in its main thread. But as
the services runs in its own process, you need to use some interprocess
communication (IPC) to communicate to your service from other parts.
• Even if the service runs in its own process, you need to use
asynchronous processing to perform network access, because Android
does not allow network access in the main thread of a process. 47
Communicating with services
• Using Intent data: The service receives the intent data from the starting
Android component and performs its work
• Using receiver: You can also use broadcast events and registered receivers for
the communication.
• Activity binding to local service: If the service is started in the same process as
the activity, the activity can directly bind to the service.
• Handler and ResultReceiver or Messenger : If the service should be
communicating back to the activity, it can receive an object of type Messenger
via the Intent data it receives from the activity. If the Messenger is bound to a
Handler in the activity, the service can send objects of type Message to the
activity.
• AIDL for services in a different process :To bind to a service which runs in a
different process, you need to use Inter Process Communication (IPC) as the
data needs to be sent between different processes. 48
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
25
Service communicationUsing BroadcastReceiver
49
Service communicationUsing BroadcastReceiver
50
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
26
AsyncQueryHandler
51
AsyncQueryHandler
• Asynchronous operations on a ContentResolver
o Query
o Insert
o Delete
o Update
• Wraps a HandlerThread
• Cons
• No cursor management
• No content observation
• No data retention on configuration changes
• Background thread can’t be forced to quit
52
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
27
How it works
53
UIThread
BGThread
new AsyncQueryHandler();1
startQuery();startInsert();startUpdate();startDelete();
2
onQueryComplete();onInsertComplete();onUpdateComplete();onDeleteComplete();
3
DB operations
AsyncQueryHandler sample class
54
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
28
AsyncQueryHandler demo
55
AsyncQueryHandler demo
56
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
29
Loader
57
Loader
• API added in Honeycomb Available in compatibility package
• Load data in a background thread
• Observes data changes
• Retained on configuration changes
• Connected to the Activity and Fragment lifecycles
• Pitfalls
o Data loading will stop when Activity/Fragment is destroyed
o Http requests not finished
• Good Use Cases
o Loading data from Content Providers.
58
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
30
Basics
59
Data Source
Loader
1 Load data in BG 2 Observe data
3 Lifecycle management 4 Retained on configuration change
Any Data Source
ContentProvide
r
CustomLoader
CursorLoader
How it works
60
http
://vo
vanh
ai.w
ordp
ress
.com
/
23/03/2016
31
Summary
61
Concurrent executionConcurrent execution
Thread Executor
HandlerThread
One shot tasksOne shot tasks
AsyncTask
Subsequent executionSubsequent execution
AsyncTask<Void, Void, Void>AsyncTask.execute(Runnable)AsyncTask<Void, Void, Void>AsyncTask.execute(Runnable)
One task with UI callbackOne task with UI callback
Service
Activity lifecycle independent tasksActivity lifecycle independent tasks
IntentService
“On demand”“On demand”“Continuous”“Continuous”
AsyncQuery
Handler
Asynchronous CRUDAsynchronous CRUD
Loader
Load data from CPData observingLoad data from CPData observing
Full CRUDFull CRUD
“newSingleThreadExecutor”Execute Message and RunnableBetter clean up
“newSingleThreadExecutor”Execute Message and RunnableBetter clean up
Execution abstractionRepetitive tasksConcurrent executionSequential executionExecution managementTask management
Execution abstractionRepetitive tasksConcurrent executionSequential executionExecution managementTask management
Task controlTask control
CustomLoaderCustomLoader
62
http
://vo
vanh
ai.w
ordp
ress
.com
/