asynchronous techniques //vovanhai.files.wordpress.com/2016/03/5-asynchronous-techniques... ·...
TRANSCRIPT
09/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
/
09/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
/
09/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
/
09/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
/
09/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
/
09/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
/
09/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
/
09/03/2016
8
Thread - Example
15
Dis-advantages and using
• Pitfalls
o Non-retained threads
o Missing cancellation policy
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
/
09/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
/
09/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
/
09/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
HandlerThread
22
http
://vo
vanh
ai.w
ordp
ress
.com
/
09/03/2016
12
t = new HandlerThread("BgThread");t.start();
1
Handler h = new Handler(t.getLooper()) {@Overridepublic void handleMessage(Message msg) {
//Process message}
};
2
HandlerThread
• 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
/
09/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
/
09/03/2016
14
Example – using messgae
27
Using post
28
http
://vo
vanh
ai.w
ordp
ress
.com
/
09/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
30
http
://vo
vanh
ai.w
ordp
ress
.com
/
09/03/2016
16
AsyncTask
• 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
/
09/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
/
09/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
/
09/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
/
09/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
/
09/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
/
09/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
/
09/03/2016
23
• Define your service in AndroidManifest.xml file
45
AsyncQueryHandler
46
http
://vo
vanh
ai.w
ordp
ress
.com
/
09/03/2016
24
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
47
How it works
48
UIThread
BGThread
new AsyncQueryHandler();1
startQuery();startInsert();startUpdate();startDelete();
2
onQueryComplete();onInsertComplete();onUpdateComplete();onDeleteComplete();
3
DB operations
http
://vo
vanh
ai.w
ordp
ress
.com
/
09/03/2016
25
Example
49
Loader
50
http
://vo
vanh
ai.w
ordp
ress
.com
/
09/03/2016
26
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.
51
Basics
52
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
http
://vo
vanh
ai.w
ordp
ress
.com
/
09/03/2016
27
How it works
53
Summary
54
http
://vo
vanh
ai.w
ordp
ress
.com
/
09/03/2016
28
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
55
http
://vo
vanh
ai.w
ordp
ress
.com
/