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://vovanhai.wordpress.com/
28
Embed
Asynchronous Techniques //vovanhai.files.wordpress.com/2016/03/5-asynchronous-techniques... · 2016/3/5 · o Lost thread safety when switching from sequential to concurrent execution
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
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
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