SlideShare a Scribd company logo
Processes and Threads
TK2323 Mobile Programming
Sem 1 2017/2018
Lam Meng Chun
lammc@ukm.edu.my (G-02-04)
Outline
Processes
Foreground Process
Visible Process
Service Process
Cached Process
Thread
Runnable/Worker Thread
(Optional)
AsyncTask
Handler, Looper,
Message (Optional)
2
Processes and Threads
3
Process
▹When an application component starts and the
application does not have any other components
running, the Android system starts a new Linux
process for the application with a single thread of
execution.
▹By default, all components of the same application
run in the same process and thread (called the "main"
thread/ UI thread).
4
Process
▹If an application component starts and there
already exists a process for that application (because
another component from the application exists), then
the component is started within that process and
uses the same thread of execution.
▹However, you can arrange for different components
in your application to run in separate processes, and
you can create additional threads for any process.
5
6
Process
6
Process
A new Linux process for the application with a single thread of execution
7
Process
▹By default, all components of the same application
run in the same process and most applications should
not change this.
▹However, if you find that you need to control which
process a certain component belongs to, you can do
so in the manifest file.
8
9 Processes
▹The manifest entry for each type of component element—
<activity>, <service>, <receiver>, and <provider> —supports
an android:process attribute that can specify a process in
which that component should run.
▹You can set this attribute so that each component runs in
its own process or so that some components share a process
while others do not.
10 Processes
▹You can also set android:process so that components of
different applications run in the same process—provided
that the applications share the same Linux user ID and are
signed with the same certificates.
11 Question
▹How many process does an application can run?
12 Processes
▹Android might decide to shut down a process at some
point, when memory is low and required by other
processes that are more immediately serving the user.
▹Application components running in the process that's
killed are consequently destroyed.
▹A process is started again for those components when
there's again work for them to do.
13 Processes
▹The Android system tries to maintain an application
process for as long as possible, but eventually needs to
remove old processes to reclaim memory for new or more
important processes.
14 Processes
▹To determine which processes to keep and which to kill,
the system places each process into an "importance
hierarchy" based on the components running in the process
and the state of those components.
▹Processes with the lowest importance are eliminated first,
then those with the next lowest importance, and so on, as
necessary to recover system resources.
15
Processes:
Five levels in
the
importance
hierarchy
Foreground
Process
Visible Process
Service Process
Cached process
16
Processes: Foreground
Process
▹A process that is required for what the user is currently doing.
▹It hosts an Activity that the user is interacting with (the Activity's
onResume() method has been called).
▹It hosts a Service that's bound to the activity that the user is
interacting with.
▹It hosts a Service that's running "in the foreground"—the
service has called startForeground().
17
Processes: Foreground
Process
▹A process that is required for what the user is currently
doing.
▹Various application components can cause its containing
process to be considered foreground in different ways.
18
Processes: Foreground
Process
▹It is running an
Activity at the top of
the screen that the user
is interacting with (its
onResume() method
has been called).
▹It has a
BroadcastReceiver that
is currently running (its
BroadcastReceiver.onR
eceive() method is
executing).
▹It has a Service that is
currently executing
code in one of its
callbacks
(Service.onCreate(),
Service.onStart(), or
Service.onDestroy()).
▹A process is considered to be in the foreground if any of
the following conditions hold:
19
Android
Components
Activity-
LifeCycle
20 Processes: Visible Process
▹A visible process is doing work that the user is currently
aware of, so killing it would have a noticeable negative
impact on the user experience.
▹A visible process is considered extremely important and
will not be killed unless doing so is required to keep all
foreground processes running.
21 Processes: Visible Process
▸It is running an Activity
that is visible to the user
on-screen but not in the
foreground (its onPause()
method has been called).
This may occur, for
example, if the foreground
Activity is displayed as a
dialog that allows the
previous Activity to be
seen behind it.
▹It has a Service that is
running as a foreground
service, through
Service.startForeground()
(which is asking the
system to treat the service
as something the user is
aware of, or essentially
visible to them).
▸It is hosting a service
that the system is using
for a particular feature
that the user is aware (live
wallpaper, input method
service, etc.)
▹A process is considered foreground in the following
conditions:
22 Processes: Service process
▹A process that is running a service that has been started with
the startService() method and does not fall into either of the two higher
categories.
▸User is not directly interacting
▹Although service processes are not directly tied to anything the user
sees, they are generally doing things that the user cares about (such as
playing music in the background or downloading data on the network),
▹so the system keeps them running unless there's not enough memory
to retain them along with all foreground and visible processes.
23 Processes: Service process
▹Services that have been running for a long time (such as
30 minutes or more) may be demoted in importance to
allow their process to drop to the cached Least Recently
Used (LRU) list described next.
▹This helps avoid situations where very long running
services with memory leaks or other problems consume so
much RAM that they prevent the system from making
effective use of cached processes.
24 Cached Process
▹A cached process is one that is not currently needed, so
the system is free to kill it as desired when memory is
needed elsewhere.
▹In a normally behaving system, these are the only
processes involved in memory management: a well running
system will have multiple cached processes always available
(for more efficient switching between applications) and
regularly kill the oldest ones as needed.
25 Cached Process
▹These processes often hold one or more Activity instances that are not
currently visible to the user (the onStop() method has been called and
returned).
▹Provided they implement their Activity life-cycle correctly (see Activity
for more details),
▹when the system kills such processes it will not impact the user's
experience when returning to that app:
▹it can restore the previously saved state when the associated activity is
recreated in a new process.
26
Cached Process (LRU- Least
Recently Used_
▹These processes are kept in a pseudo-LRU list, where the
last process on the list is the first killed to reclaim memory.
▹The exact policy of ordering on this list is an
implementation detail of the platform, but generally it will
try to keep more useful processes (one hosting the user's
home application, the last activity they saw, etc) before
other types of processes.
27
Cached Process (LRU- Least
Recently Used_
▹Other policies for killing processes may also be applied:
hard limits on the number of processes allowed, limits on
the amount of time a process can stay continually cached,
etc.
28
Question
▹Which process will be the first to kill by Android OS?
29 Processes (Service Tips)
▹Because a process running a service is ranked higher than a process
with background activities, an activity that initiates a long-running
operation might do well to start a service for that operation, rather than
simply create a worker thread—particularly if the operation will likely
outlast the activity.
▹For example, an activity that's uploading a picture to a web site should
start a service to perform the upload so that the upload can continue in
the background even if the user leaves the activity.
▹Using a service guarantees that the operation will have at least
"service process" priority, regardless of what happens to the activity.
30 Processes
▹Process running a service is ranked higher [as a Service
Process] than a process that doesn’t have a service [uses
threads for long running operations]
▹Hence, downloading an image from a worker thread using
a Service is better than downloading without a service.
31
Thread
32
33 Threads
▹When an application is launched, the system creates a thread of
execution for the application, called "main“/ “UI” thread.
▹This thread is very important because it is in charge of
dispatching events to the appropriate user interface widgets,
including drawing events.
▹It is also the thread in which your application interacts with
components from the Android UI toolkit ( components from the
android.widget and android.view packages ).
34 Threads
1. On certain occasions a single app may want to do more than one
‘thing’ at the same time. For instance, show an animation, download
a large file from a website, and maintain a responsive UI for the user
to enter data.
▸One solution is to have the app run those individual concurrent
actions in separate threads.
2. Threads are the smallest sequence of programmed instructions
that can be managed independently by operating system
3. They are units of computation that run simultaneously within a
process
35 Threads
▹The system does not create a separate thread for each
instance of a component.
▹All components that run in the same process are
instantiated in the UI thread, and system calls to each
component are dispatched from that thread.
▹Consequently, methods that respond to system callbacks
(such as onKeyDown() to report user actions or a lifecycle
callback method) always run in the UI thread of the process.
36
Threads
▹For instance, when the user touches a button on the screen, your
app's UI thread dispatches the touch event to the widget, which in
turn sets its pressed state and posts an invalidate request to the
event queue.
▹The UI thread dequeues the request and notifies the widget that
it should redraw itself.
Change the
color of the
text view
Touch
Button
Main Thread
37 Threads
▹When your app performs intensive work in response to user
interaction, this single thread model can yield poor performance
unless you implement your application properly.
▹Specifically, if everything is happening in the UI thread,
performing long operations such network access, database
queries, complicated calculations, accessing big files will block
the whole UI.
▹When the Main thread is blocked, no events can be
dispatched, including drawing events. From the user's
perspective, the application appears to hang.
38 Threads
▹Even worse, if the UI thread is blocked for more than a
few seconds (about 5 seconds currently) the user is
presented with the infamous “application not responding"
(ANR) dialog.
▹In practice, users will notice input delays and UI pauses of
more than a couple of hundred milliseconds.
▹The user might then decide to quit your application and
uninstall it if they are unhappy.
39 Threads
Change the
color of the
text view
Touch
Button
Long
Running
Process
Touch
Button
Main Thread
Wait until the process complete running,
only then the UI will respond again.
(Button will not work until the process
has finished)
40 Threads
Change the
color of the
text view
Touch
Button
Long
Running
Process
Touch
Button
Main Thread
Separated
Thread
Update Result after finish
running the process
41
Lecturer
(User)
MultiThreads
Separated
Thread
(Member)
Assignment
1
(0.1 S)
Assignment
3
(6 s)
Assignment
2
(0.5 S)
Assignment
4
(3 S) Separated
Thread
(Member)
Separated
Thread
(Member)
Separated
Thread
(Member)
Separated
Thread
(Member)
Main Thread
(Phantom/
UI Freeze)
Main Thread
(Team
Leader)
42 Threads
▹Additionally, the Andoid UI toolkit is not thread-safe. So, you
must not manipulate your UI from a worker thread—you must do
all manipulation to your user interface from the UI thread.
▹Thread-safe code is code that will work even if many Threads
are executing it simultaneously.
▹Thus, there are simply two rules to Android's single thread
model:
▸Do not block the UI thread
▸Do not access the Android UI toolkit from outside the UI
thread
43
Worker or Background
threads
▹Because of the single thread model described above, it's
vital to the responsiveness of your application's UI that you
do not block the UI thread.
▹If you have operations to perform that are not
instantaneous, you should make sure to do them in separate
threads ("background" or "worker" threads).
Thread-Example
Code
44
45
Example
public void onClick(View v) {
new Thread(new Runnable() {
});
}
46
Example public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
}
});
}
47
Example public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
// long running process
}
}).start();
}
48 Example
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
Bitmap b =
loadImageFromNetwork("http://example.com/image.png");
mImageView.setImageBitmap(b);
}
}).start();
}
What’s wrong???
49
Worker or Background
threads
▹To fix this problem, Android offers several ways to access
the UI thread from other threads. Here is a list of methods
that can help:
▸Activity.runOnUiThread(Runnable)
▸View.post(Runnable)
▸View.postDelayed(Runnable, long)
50 Example
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
Bitmap b =
loadImageFromNetwork("http://example.com/image.png");
mImageView.setImageBitmap(b);
}
}).start();
}
What’s wrong???
51
Worker or Background
threads
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
final Bitmap bitmap =
loadImageFromNetwork("http://example.com/image.png");
mImageView.post(new Runnable() {
});
}
}).start();
}
52
Worker or Background
threads
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
final Bitmap bitmap =
loadImageFromNetwork("http://example.com/image.png");
mImageView.post(new Runnable() {
public void run() {
}
});
}
}).start();
}
53
Worker or Background
threads
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
final Bitmap bitmap =
loadImageFromNetwork("http://example.com/image.png");
mImageView.post(new Runnable() {
public void run() {
mImageView.setImageBitmap(bitmap);
}
});
}
}).start();
}
54
Worker or Background
threads
▹Activity.runOnUiThread(Runnable)
▸Runs the specified action on the UI thread.
▸If the current thread is the UI thread, then the action is
executed immediately.
▸If the current thread is not the UI thread, the action is
posted to the event queue of the UI thread.
Activity.runOnUiThread(Runnable)
56 Example
private void runThread() {
new Thread() {
public void run() {
while (i++ < 1000) {
runOnUiThread(new Runnable() {
@Override
public void run() {
btn.setText("#" + i);
}
});
Thread.sleep(300);
}
}
}.start();
}
57
private void runThread() {
new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
btn.setText("#" + i);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
View.post (Runnable)
59
Worker or Background
threads
▹View.post (Runnable)
▸Causes the Runnable to be added to the message
queue.
▸The runnable will be run on the user interface thread.
60 Example
Runnable mSetEditText = new Runnable() {
@Override
public void run() {
}
};
new Thread(mSetEditText ).start();
61
new Thread(mSetEditText).start();
Runnable mSetEditText = new Runnable() {
int i = 0;
@Override
public void run() {
while (i < 1000000) {
i++;
}
et_text.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
et_text.setText("i:" + i);
}
});
}
};
View.postDelayed(Runnable)
63
Worker or Background
threads
▹View.postDelayed(Runnable)
▸Causes the Runnable to be added to the message
queue,
▸to be run after the specified amount of time elapses
▸The runnable will be run on the user interface thread.
64 Example
Handler mHandler;
mHandler =new Handler();
Runnable mSetEditText = new Runnable() {
@Override public void run() {
et_text.setText(“Delayed”);
}
};
65
Handler mHandler;
mHandler =new Handler();
Runnable mSetEditText = new Runnable() {
@Override public void run() {
et_text.setText(“Delayed”);
}
};
btt_set_text_delayed.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
mHandler.postDelayed(mSetEditText , 2000);
}
});
AsyncTask
67
Worker or Background
threads: Using AsyncTask
▹This kind of code can get complicated and difficult to
maintain
▹AsyncTask allows you to perform asynchronous work on
your user interface.
▹It performs the blocking operations in a worker thread
and then publishes the results on the UI thread, without
requiring you to handle threads and/or handlers yourself.
68
Worker or Background
threads: Using AsyncTask
▹AsyncTask is designed to be a helper class around Thread and
Handler and does not constitute a generic threading framework.
▹AsyncTasks should ideally be used for short operations (a few
seconds at the most.)
▹If you need to keep threads running for long periods of time, it is
highly recommended you use the various APIs provided by the
java.util.concurrent package such as Executor,
ThreadPoolExecutor and FutureTask.
69
Worker or Background
threads: Using AsyncTask
▹An asynchronous task is defined by a computation that
runs on a background thread and whose result is published
on the UI thread.
70
Worker or Background
threads: Using AsyncTask
▹Params,
▹the type of the
parameters sent to the
task upon execution.
▹Progress,
▹the type of the
progress units
published during the
background
computation
▹Result,
▹the type of the result
of the background
computation.
▹An asynchronous task is defined by 3 generic types, called
• Params,
• Progress
• Result
71
Worker or Background
threads: Using AsyncTask
▹4 steps, called
▸onPreExecute
▸doInBackground
▸onProgreeUpdate
▸onPostExecute
72
Worker or Background
threads: Using AsyncTask
▹onPreExecute
▸invoked on the UI thread before the task is executed.
▸This step is normally used to setup the task, for
instance by showing a progress bar in the user interface.
▸Runs on the UI thread before
doInBackground(Params...)
73
Worker or Background
threads: Using AsyncTask
▹doInBackground
▸invoked on the background thread immediately after
onPreExecute() finishes executing
▸This method will be executed on the background Thread, so place
your long-running code here, don’t attempt to interact with UI
objects within this handler.
▸It takes a set of parameter of the type defined in your class
implementation
▸You can use the publishProgress() method from within this handler
to pass parameter values to the onProgressUpdate() handler,
▸and when your background task is complete, you can return the
final result as a parameter to the onPostExecute() handler, which can
update the UI accordingly.
74
Worker or Background
threads: Using AsyncTask
▹onProgreeUpdate
▸Override this handler to update the UI with interim
progress updates.
▸This handler receives the set of parameters passed in to
▸publishProgress (typically within the doInBackground
handler).
▸This handler is synchronized with the GUI Thread when
executed, so you can safely modify UI elements.
75
Worker or Background
threads: Using AsyncTask
▹onPostExecute
▸When doInBackground() has completed, the return
value from that method is passed in to this event handler.
▸Use this handler to update the UI when your
asynchronous task has completed.
▸This handler is synchronized with the GUI Thread when
executed, so you can safely modify UI elements.
76
private class DownloadFilesTask extends AsyncTask<Params, Progress, Result> {
protected void onPreExecute() {
// Runs on the UI thread before doInBackground()
}
protected Long doInBackground(Params... urls) {
// Perform an operation on a background thread
doSomethingLongRunning();
return something;
}
protected void onProgressUpdate(Progress... progress) {
// Runs on UI thread after publishProgress(Progress...) is invoked
// from doInBackground()
pb.setProgress(progress[0]));
}
protected void onPostExecute(Result result) {
// Runs on the UI thread after doInBackground()
showDialog("Downloaded " + result + " bytes");
}
}
77 Example
params progress result
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
tv_status.setText(“Start downloading");
}
.
.
.
}
78 Example
params progress result
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
Looping
{
DownloadPicture();
publishProgress((int)howManyHasDownloaded));
}
return totalNumberOfPic;
}
protected void onProgressUpdate(Integer... progress) {
tv_status.setText(“Downloading: ”+progress[0]));
}
protected void onPostExecute(Long result) {
tv_status.setText(“Downloaded " + result + " pic");
}
}
79 Example
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
tv_status.setText(progress[0]));
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
80
Worker or
Background
threads:
AsyncTask
▹AsyncTask is not bonded to the activity
life cycle
▹The virtual machine will hold on the
activity object as long as the AsyncTask is
running
▹AsyncTask is running even the activity is
destroyed
▹Thus there is a chance multiple
AsyncTask is running in the same time
▸Portrait
▸Landscape
▹Not suitable for the long running
operation (>few seconds)
▹Use service instead
Activity Async Task
Handler, Looper,
Runnable (Optional)
82 Introduction
▹Android maintains a MessageQueue (message loop) on the main thread which
basically contains a list of Messages or Runnables (set of executable code) that the
Looper dispatches to appropriate Handlers.
▹When a process is created for your application, its main thread is dedicated to
running a message queue that takes care of managing the top-level application
objects (activities, broadcast receivers, etc) and any windows they create.
▹You can create your own threads, and communicate back with the main application
thread through a Handler. This is done by calling the
same post or sendMessage methods, but from your new thread.
▹The given Runnable or Message will then be scheduled in the Handler's message
queue and processed when appropriate.
83
Message Queue
Looper, Handler, Message
Queue
message message message message
Looper
message
Looper
message
Handler
Looper
message
Looper contain message and
associated with the Message
Queue. So it could be run
into the thread
Handler contain
looper
Handler determine when it should dispatch the
message into the message queue and execute them
as they come out of the message queue.
postAtTime(Runnable, long)…
84 Handler
▹A Handler allows you 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.
▹When you create a new Handler, it is bound to the thread /
message queue of the thread that is creating it -- from that point
on, it will deliver messages and runnables to that message queue
and execute them as they come out of the message queue.
85 Handler
▹There are two main uses for a Handler:
▸(1) to schedule messages and runnables to be executed
as some point in the future; and
▸(2) to enqueue/add an action to be performed on a
different thread than your own.
86 Handler
▹When posting or sending to a Handler, you can either
allow the item to be processed as soon as the message
queue is ready to do so, or specify a delay before it gets
processed or absolute time for it to be processed.
▸post(Runnable)
▸postAtTime(Runnable, long)
▸postDelayed(Runnable, long)
▸Handler.post...
87 MessageQueue
▹Low-level class holding the list of messages to be
dispatched by a Looper to the Handlers.
▹Messages are not added directly to a MessageQueue, but
rather through Handler objects associated with the Looper.
▹MessageQueue (message loop) on the main thread which
basically contains a list of Messages or Runnables (set of
executable code) that the Looper dispatches to appropriate
Handlers.
88 Looper
▹Class used to run a message loop for a thread.
▹The main thread is a message loop and has a looper.
▹Threads by default do not have a message loop associated with
them; to create one, call prepare() in the thread that is to run the
loop, and then loop() to have it process messages until the loop is
stopped.
▹Most interaction with a message loop is through the Handler
class.
89 Example
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
90 Handler
Process Send
91 Handler, Looper, Runnable
▹More information
▸http://codetheory.in/android-handlers-runnables-
loopers-messagequeue-handlerthread/
▸http://developer.android.com/reference/android/os/H
andler.html
92 Reminder
▹Mobile App Development Project
93 Thanks

More Related Content

What's hot

Android structure
Android structureAndroid structure
Android structure
Kumar
 
Corba
CorbaCorba
Linux operating system
Linux operating systemLinux operating system
Linux operating system
ITz_1
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
Android application structure
Android application structureAndroid application structure
Android application structure
Alexey Ustenko
 
Linux commands
Linux commandsLinux commands
Linux commands
Mannu Khani
 
Multiprocessor Systems
Multiprocessor SystemsMultiprocessor Systems
Multiprocessor Systems
vampugani
 
Presentation on Android application
Presentation on Android applicationPresentation on Android application
Presentation on Android application
Atibur Rahman
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
Tanmoy Barman
 
Android Architecture
Android ArchitectureAndroid Architecture
Android Architecture
deepakshare
 
DLL(dynamic link library)
DLL(dynamic link library)DLL(dynamic link library)
DLL(dynamic link library)
pooja_doshi
 
Client Server Architecture
Client Server ArchitectureClient Server Architecture
Client Server Architecture
Rence Montanes
 
JAVA PROGRAMMING
JAVA PROGRAMMING JAVA PROGRAMMING
JAVA PROGRAMMING
Niyitegekabilly
 
Android UI
Android UIAndroid UI
Android UI
nationalmobileapps
 
Windows for Everyone(Operating System)
Windows for Everyone(Operating System)Windows for Everyone(Operating System)
Windows for Everyone(Operating System)
Waleed Khan
 
Tk2323 lecture 1 introduction to mobile application
Tk2323 lecture 1   introduction to mobile applicationTk2323 lecture 1   introduction to mobile application
Tk2323 lecture 1 introduction to mobile application
MengChun Lam
 
File Management in Operating System
File Management in Operating SystemFile Management in Operating System
File Management in Operating System
Janki Shah
 
Operating system architecture
Operating system architectureOperating system architecture
Operating system architecture
Sabin dumre
 
Anatomy of android application
Anatomy of android applicationAnatomy of android application
Anatomy of android application
Nikunj Dhameliya
 
Introduction to Unix operating system Chapter 1-PPT Mrs.Sowmya Jyothi
Introduction to Unix operating system Chapter 1-PPT Mrs.Sowmya JyothiIntroduction to Unix operating system Chapter 1-PPT Mrs.Sowmya Jyothi
Introduction to Unix operating system Chapter 1-PPT Mrs.Sowmya Jyothi
Sowmya Jyothi
 

What's hot (20)

Android structure
Android structureAndroid structure
Android structure
 
Corba
CorbaCorba
Corba
 
Linux operating system
Linux operating systemLinux operating system
Linux operating system
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Android application structure
Android application structureAndroid application structure
Android application structure
 
Linux commands
Linux commandsLinux commands
Linux commands
 
Multiprocessor Systems
Multiprocessor SystemsMultiprocessor Systems
Multiprocessor Systems
 
Presentation on Android application
Presentation on Android applicationPresentation on Android application
Presentation on Android application
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Android Architecture
Android ArchitectureAndroid Architecture
Android Architecture
 
DLL(dynamic link library)
DLL(dynamic link library)DLL(dynamic link library)
DLL(dynamic link library)
 
Client Server Architecture
Client Server ArchitectureClient Server Architecture
Client Server Architecture
 
JAVA PROGRAMMING
JAVA PROGRAMMING JAVA PROGRAMMING
JAVA PROGRAMMING
 
Android UI
Android UIAndroid UI
Android UI
 
Windows for Everyone(Operating System)
Windows for Everyone(Operating System)Windows for Everyone(Operating System)
Windows for Everyone(Operating System)
 
Tk2323 lecture 1 introduction to mobile application
Tk2323 lecture 1   introduction to mobile applicationTk2323 lecture 1   introduction to mobile application
Tk2323 lecture 1 introduction to mobile application
 
File Management in Operating System
File Management in Operating SystemFile Management in Operating System
File Management in Operating System
 
Operating system architecture
Operating system architectureOperating system architecture
Operating system architecture
 
Anatomy of android application
Anatomy of android applicationAnatomy of android application
Anatomy of android application
 
Introduction to Unix operating system Chapter 1-PPT Mrs.Sowmya Jyothi
Introduction to Unix operating system Chapter 1-PPT Mrs.Sowmya JyothiIntroduction to Unix operating system Chapter 1-PPT Mrs.Sowmya Jyothi
Introduction to Unix operating system Chapter 1-PPT Mrs.Sowmya Jyothi
 

Similar to Tk2323 lecture 11 process and thread

Process Management in Android
Process Management in AndroidProcess Management in Android
Process Management in Android
Shrey Verma
 
Threads handlers and async task, widgets - day8
Threads   handlers and async task, widgets - day8Threads   handlers and async task, widgets - day8
Threads handlers and async task, widgets - day8
Utkarsh Mankad
 
Analysis Of Process Structure In Windows Operating System
Analysis Of Process Structure In Windows Operating SystemAnalysis Of Process Structure In Windows Operating System
Analysis Of Process Structure In Windows Operating System
Darian Pruitt
 
Lesson 6 Processor Management
Lesson 6 Processor ManagementLesson 6 Processor Management
Lesson 6 Processor Management
Laguna State Polytechnic University
 
Process Management Operating Systems .pptx
Process Management        Operating Systems .pptxProcess Management        Operating Systems .pptx
Process Management Operating Systems .pptx
SAIKRISHNADURVASULA2
 
Chapter 5
Chapter 5Chapter 5
Android application development
Android application developmentAndroid application development
Android application development
Md. Mujahid Islam
 
Operating system
Operating systemOperating system
Operating system
Keshav Kasliwal
 
Operating System
Operating SystemOperating System
Operating System
guest8b0942
 
Operating system Concepts
Operating system Concepts Operating system Concepts
Operating system Concepts
RANVIJAY GAUR
 
Advanced computer architecture lesson 1 and 2
Advanced computer architecture lesson 1 and 2Advanced computer architecture lesson 1 and 2
Advanced computer architecture lesson 1 and 2
Ismail Mukiibi
 
Dori waldman android _course_2
Dori waldman android _course_2Dori waldman android _course_2
Dori waldman android _course_2
Dori Waldman
 
Compyter system softwere
Compyter system softwereCompyter system softwere
Compyter system softwere
Alamin Hossain Miraje
 
Dori waldman android _course
Dori waldman android _courseDori waldman android _course
Dori waldman android _course
Dori Waldman
 
Os
OsOs
Os
OsOs
Understanding Basics of OS
Understanding Basics of OSUnderstanding Basics of OS
Understanding Basics of OS
E.M.G.yadava womens college
 
Ch2_Processes_and_process_management_1.ppt
Ch2_Processes_and_process_management_1.pptCh2_Processes_and_process_management_1.ppt
Ch2_Processes_and_process_management_1.ppt
Mohammad Almuiet
 
Operating system
Operating systemOperating system
Operating system
chetan handa
 
Android OS
Android OSAndroid OS
Android OS
Vishal Sapariya
 

Similar to Tk2323 lecture 11 process and thread (20)

Process Management in Android
Process Management in AndroidProcess Management in Android
Process Management in Android
 
Threads handlers and async task, widgets - day8
Threads   handlers and async task, widgets - day8Threads   handlers and async task, widgets - day8
Threads handlers and async task, widgets - day8
 
Analysis Of Process Structure In Windows Operating System
Analysis Of Process Structure In Windows Operating SystemAnalysis Of Process Structure In Windows Operating System
Analysis Of Process Structure In Windows Operating System
 
Lesson 6 Processor Management
Lesson 6 Processor ManagementLesson 6 Processor Management
Lesson 6 Processor Management
 
Process Management Operating Systems .pptx
Process Management        Operating Systems .pptxProcess Management        Operating Systems .pptx
Process Management Operating Systems .pptx
 
Chapter 5
Chapter 5Chapter 5
Chapter 5
 
Android application development
Android application developmentAndroid application development
Android application development
 
Operating system
Operating systemOperating system
Operating system
 
Operating System
Operating SystemOperating System
Operating System
 
Operating system Concepts
Operating system Concepts Operating system Concepts
Operating system Concepts
 
Advanced computer architecture lesson 1 and 2
Advanced computer architecture lesson 1 and 2Advanced computer architecture lesson 1 and 2
Advanced computer architecture lesson 1 and 2
 
Dori waldman android _course_2
Dori waldman android _course_2Dori waldman android _course_2
Dori waldman android _course_2
 
Compyter system softwere
Compyter system softwereCompyter system softwere
Compyter system softwere
 
Dori waldman android _course
Dori waldman android _courseDori waldman android _course
Dori waldman android _course
 
Os
OsOs
Os
 
Os
OsOs
Os
 
Understanding Basics of OS
Understanding Basics of OSUnderstanding Basics of OS
Understanding Basics of OS
 
Ch2_Processes_and_process_management_1.ppt
Ch2_Processes_and_process_management_1.pptCh2_Processes_and_process_management_1.ppt
Ch2_Processes_and_process_management_1.ppt
 
Operating system
Operating systemOperating system
Operating system
 
Android OS
Android OSAndroid OS
Android OS
 

More from MengChun Lam

Tk2323 lecture 10 sensor
Tk2323 lecture 10   sensorTk2323 lecture 10   sensor
Tk2323 lecture 10 sensor
MengChun Lam
 
Tk2323 lecture 9 api json
Tk2323 lecture 9   api jsonTk2323 lecture 9   api json
Tk2323 lecture 9 api json
MengChun Lam
 
Tk2323 lecture 4 ui ux
Tk2323 lecture 4   ui uxTk2323 lecture 4   ui ux
Tk2323 lecture 4 ui ux
MengChun Lam
 
Tk2323 lecture 6 fragment (new)
Tk2323 lecture 6   fragment (new)Tk2323 lecture 6   fragment (new)
Tk2323 lecture 6 fragment (new)
MengChun Lam
 
Tk2323 lecture 7 data storage
Tk2323 lecture 7   data storageTk2323 lecture 7   data storage
Tk2323 lecture 7 data storage
MengChun Lam
 
Tk2323 lecture 5 material design &amp; recycler view
Tk2323 lecture 5   material design &amp; recycler viewTk2323 lecture 5   material design &amp; recycler view
Tk2323 lecture 5 material design &amp; recycler view
MengChun Lam
 
Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql
MengChun Lam
 
Tk2323 lecture 3 intent
Tk2323 lecture 3   intentTk2323 lecture 3   intent
Tk2323 lecture 3 intent
MengChun Lam
 
Tk2323 lecture 2 ui
Tk2323 lecture 2   uiTk2323 lecture 2   ui
Tk2323 lecture 2 ui
MengChun Lam
 

More from MengChun Lam (9)

Tk2323 lecture 10 sensor
Tk2323 lecture 10   sensorTk2323 lecture 10   sensor
Tk2323 lecture 10 sensor
 
Tk2323 lecture 9 api json
Tk2323 lecture 9   api jsonTk2323 lecture 9   api json
Tk2323 lecture 9 api json
 
Tk2323 lecture 4 ui ux
Tk2323 lecture 4   ui uxTk2323 lecture 4   ui ux
Tk2323 lecture 4 ui ux
 
Tk2323 lecture 6 fragment (new)
Tk2323 lecture 6   fragment (new)Tk2323 lecture 6   fragment (new)
Tk2323 lecture 6 fragment (new)
 
Tk2323 lecture 7 data storage
Tk2323 lecture 7   data storageTk2323 lecture 7   data storage
Tk2323 lecture 7 data storage
 
Tk2323 lecture 5 material design &amp; recycler view
Tk2323 lecture 5   material design &amp; recycler viewTk2323 lecture 5   material design &amp; recycler view
Tk2323 lecture 5 material design &amp; recycler view
 
Tk2323 lecture 7 sql
Tk2323 lecture 7   sql Tk2323 lecture 7   sql
Tk2323 lecture 7 sql
 
Tk2323 lecture 3 intent
Tk2323 lecture 3   intentTk2323 lecture 3   intent
Tk2323 lecture 3 intent
 
Tk2323 lecture 2 ui
Tk2323 lecture 2   uiTk2323 lecture 2   ui
Tk2323 lecture 2 ui
 

Tk2323 lecture 11 process and thread

  • 1. Processes and Threads TK2323 Mobile Programming Sem 1 2017/2018 Lam Meng Chun lammc@ukm.edu.my (G-02-04)
  • 2. Outline Processes Foreground Process Visible Process Service Process Cached Process Thread Runnable/Worker Thread (Optional) AsyncTask Handler, Looper, Message (Optional) 2
  • 4. Process ▹When an application component starts and the application does not have any other components running, the Android system starts a new Linux process for the application with a single thread of execution. ▹By default, all components of the same application run in the same process and thread (called the "main" thread/ UI thread). 4
  • 5. Process ▹If an application component starts and there already exists a process for that application (because another component from the application exists), then the component is started within that process and uses the same thread of execution. ▹However, you can arrange for different components in your application to run in separate processes, and you can create additional threads for any process. 5
  • 7. Process A new Linux process for the application with a single thread of execution 7
  • 8. Process ▹By default, all components of the same application run in the same process and most applications should not change this. ▹However, if you find that you need to control which process a certain component belongs to, you can do so in the manifest file. 8
  • 9. 9 Processes ▹The manifest entry for each type of component element— <activity>, <service>, <receiver>, and <provider> —supports an android:process attribute that can specify a process in which that component should run. ▹You can set this attribute so that each component runs in its own process or so that some components share a process while others do not.
  • 10. 10 Processes ▹You can also set android:process so that components of different applications run in the same process—provided that the applications share the same Linux user ID and are signed with the same certificates.
  • 11. 11 Question ▹How many process does an application can run?
  • 12. 12 Processes ▹Android might decide to shut down a process at some point, when memory is low and required by other processes that are more immediately serving the user. ▹Application components running in the process that's killed are consequently destroyed. ▹A process is started again for those components when there's again work for them to do.
  • 13. 13 Processes ▹The Android system tries to maintain an application process for as long as possible, but eventually needs to remove old processes to reclaim memory for new or more important processes.
  • 14. 14 Processes ▹To determine which processes to keep and which to kill, the system places each process into an "importance hierarchy" based on the components running in the process and the state of those components. ▹Processes with the lowest importance are eliminated first, then those with the next lowest importance, and so on, as necessary to recover system resources.
  • 16. 16 Processes: Foreground Process ▹A process that is required for what the user is currently doing. ▹It hosts an Activity that the user is interacting with (the Activity's onResume() method has been called). ▹It hosts a Service that's bound to the activity that the user is interacting with. ▹It hosts a Service that's running "in the foreground"—the service has called startForeground().
  • 17. 17 Processes: Foreground Process ▹A process that is required for what the user is currently doing. ▹Various application components can cause its containing process to be considered foreground in different ways.
  • 18. 18 Processes: Foreground Process ▹It is running an Activity at the top of the screen that the user is interacting with (its onResume() method has been called). ▹It has a BroadcastReceiver that is currently running (its BroadcastReceiver.onR eceive() method is executing). ▹It has a Service that is currently executing code in one of its callbacks (Service.onCreate(), Service.onStart(), or Service.onDestroy()). ▹A process is considered to be in the foreground if any of the following conditions hold:
  • 20. 20 Processes: Visible Process ▹A visible process is doing work that the user is currently aware of, so killing it would have a noticeable negative impact on the user experience. ▹A visible process is considered extremely important and will not be killed unless doing so is required to keep all foreground processes running.
  • 21. 21 Processes: Visible Process ▸It is running an Activity that is visible to the user on-screen but not in the foreground (its onPause() method has been called). This may occur, for example, if the foreground Activity is displayed as a dialog that allows the previous Activity to be seen behind it. ▹It has a Service that is running as a foreground service, through Service.startForeground() (which is asking the system to treat the service as something the user is aware of, or essentially visible to them). ▸It is hosting a service that the system is using for a particular feature that the user is aware (live wallpaper, input method service, etc.) ▹A process is considered foreground in the following conditions:
  • 22. 22 Processes: Service process ▹A process that is running a service that has been started with the startService() method and does not fall into either of the two higher categories. ▸User is not directly interacting ▹Although service processes are not directly tied to anything the user sees, they are generally doing things that the user cares about (such as playing music in the background or downloading data on the network), ▹so the system keeps them running unless there's not enough memory to retain them along with all foreground and visible processes.
  • 23. 23 Processes: Service process ▹Services that have been running for a long time (such as 30 minutes or more) may be demoted in importance to allow their process to drop to the cached Least Recently Used (LRU) list described next. ▹This helps avoid situations where very long running services with memory leaks or other problems consume so much RAM that they prevent the system from making effective use of cached processes.
  • 24. 24 Cached Process ▹A cached process is one that is not currently needed, so the system is free to kill it as desired when memory is needed elsewhere. ▹In a normally behaving system, these are the only processes involved in memory management: a well running system will have multiple cached processes always available (for more efficient switching between applications) and regularly kill the oldest ones as needed.
  • 25. 25 Cached Process ▹These processes often hold one or more Activity instances that are not currently visible to the user (the onStop() method has been called and returned). ▹Provided they implement their Activity life-cycle correctly (see Activity for more details), ▹when the system kills such processes it will not impact the user's experience when returning to that app: ▹it can restore the previously saved state when the associated activity is recreated in a new process.
  • 26. 26 Cached Process (LRU- Least Recently Used_ ▹These processes are kept in a pseudo-LRU list, where the last process on the list is the first killed to reclaim memory. ▹The exact policy of ordering on this list is an implementation detail of the platform, but generally it will try to keep more useful processes (one hosting the user's home application, the last activity they saw, etc) before other types of processes.
  • 27. 27 Cached Process (LRU- Least Recently Used_ ▹Other policies for killing processes may also be applied: hard limits on the number of processes allowed, limits on the amount of time a process can stay continually cached, etc.
  • 28. 28 Question ▹Which process will be the first to kill by Android OS?
  • 29. 29 Processes (Service Tips) ▹Because a process running a service is ranked higher than a process with background activities, an activity that initiates a long-running operation might do well to start a service for that operation, rather than simply create a worker thread—particularly if the operation will likely outlast the activity. ▹For example, an activity that's uploading a picture to a web site should start a service to perform the upload so that the upload can continue in the background even if the user leaves the activity. ▹Using a service guarantees that the operation will have at least "service process" priority, regardless of what happens to the activity.
  • 30. 30 Processes ▹Process running a service is ranked higher [as a Service Process] than a process that doesn’t have a service [uses threads for long running operations] ▹Hence, downloading an image from a worker thread using a Service is better than downloading without a service.
  • 31. 31
  • 33. 33 Threads ▹When an application is launched, the system creates a thread of execution for the application, called "main“/ “UI” thread. ▹This thread is very important because it is in charge of dispatching events to the appropriate user interface widgets, including drawing events. ▹It is also the thread in which your application interacts with components from the Android UI toolkit ( components from the android.widget and android.view packages ).
  • 34. 34 Threads 1. On certain occasions a single app may want to do more than one ‘thing’ at the same time. For instance, show an animation, download a large file from a website, and maintain a responsive UI for the user to enter data. ▸One solution is to have the app run those individual concurrent actions in separate threads. 2. Threads are the smallest sequence of programmed instructions that can be managed independently by operating system 3. They are units of computation that run simultaneously within a process
  • 35. 35 Threads ▹The system does not create a separate thread for each instance of a component. ▹All components that run in the same process are instantiated in the UI thread, and system calls to each component are dispatched from that thread. ▹Consequently, methods that respond to system callbacks (such as onKeyDown() to report user actions or a lifecycle callback method) always run in the UI thread of the process.
  • 36. 36 Threads ▹For instance, when the user touches a button on the screen, your app's UI thread dispatches the touch event to the widget, which in turn sets its pressed state and posts an invalidate request to the event queue. ▹The UI thread dequeues the request and notifies the widget that it should redraw itself. Change the color of the text view Touch Button Main Thread
  • 37. 37 Threads ▹When your app performs intensive work in response to user interaction, this single thread model can yield poor performance unless you implement your application properly. ▹Specifically, if everything is happening in the UI thread, performing long operations such network access, database queries, complicated calculations, accessing big files will block the whole UI. ▹When the Main thread is blocked, no events can be dispatched, including drawing events. From the user's perspective, the application appears to hang.
  • 38. 38 Threads ▹Even worse, if the UI thread is blocked for more than a few seconds (about 5 seconds currently) the user is presented with the infamous “application not responding" (ANR) dialog. ▹In practice, users will notice input delays and UI pauses of more than a couple of hundred milliseconds. ▹The user might then decide to quit your application and uninstall it if they are unhappy.
  • 39. 39 Threads Change the color of the text view Touch Button Long Running Process Touch Button Main Thread Wait until the process complete running, only then the UI will respond again. (Button will not work until the process has finished)
  • 40. 40 Threads Change the color of the text view Touch Button Long Running Process Touch Button Main Thread Separated Thread Update Result after finish running the process
  • 41. 41 Lecturer (User) MultiThreads Separated Thread (Member) Assignment 1 (0.1 S) Assignment 3 (6 s) Assignment 2 (0.5 S) Assignment 4 (3 S) Separated Thread (Member) Separated Thread (Member) Separated Thread (Member) Separated Thread (Member) Main Thread (Phantom/ UI Freeze) Main Thread (Team Leader)
  • 42. 42 Threads ▹Additionally, the Andoid UI toolkit is not thread-safe. So, you must not manipulate your UI from a worker thread—you must do all manipulation to your user interface from the UI thread. ▹Thread-safe code is code that will work even if many Threads are executing it simultaneously. ▹Thus, there are simply two rules to Android's single thread model: ▸Do not block the UI thread ▸Do not access the Android UI toolkit from outside the UI thread
  • 43. 43 Worker or Background threads ▹Because of the single thread model described above, it's vital to the responsiveness of your application's UI that you do not block the UI thread. ▹If you have operations to perform that are not instantaneous, you should make sure to do them in separate threads ("background" or "worker" threads).
  • 45. 45 Example public void onClick(View v) { new Thread(new Runnable() { }); }
  • 46. 46 Example public void onClick(View v) { new Thread(new Runnable() { public void run() { } }); }
  • 47. 47 Example public void onClick(View v) { new Thread(new Runnable() { public void run() { // long running process } }).start(); }
  • 48. 48 Example public void onClick(View v) { new Thread(new Runnable() { public void run() { Bitmap b = loadImageFromNetwork("http://example.com/image.png"); mImageView.setImageBitmap(b); } }).start(); } What’s wrong???
  • 49. 49 Worker or Background threads ▹To fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help: ▸Activity.runOnUiThread(Runnable) ▸View.post(Runnable) ▸View.postDelayed(Runnable, long)
  • 50. 50 Example public void onClick(View v) { new Thread(new Runnable() { public void run() { Bitmap b = loadImageFromNetwork("http://example.com/image.png"); mImageView.setImageBitmap(b); } }).start(); } What’s wrong???
  • 51. 51 Worker or Background threads public void onClick(View v) { new Thread(new Runnable() { public void run() { final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png"); mImageView.post(new Runnable() { }); } }).start(); }
  • 52. 52 Worker or Background threads public void onClick(View v) { new Thread(new Runnable() { public void run() { final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png"); mImageView.post(new Runnable() { public void run() { } }); } }).start(); }
  • 53. 53 Worker or Background threads public void onClick(View v) { new Thread(new Runnable() { public void run() { final Bitmap bitmap = loadImageFromNetwork("http://example.com/image.png"); mImageView.post(new Runnable() { public void run() { mImageView.setImageBitmap(bitmap); } }); } }).start(); }
  • 54. 54 Worker or Background threads ▹Activity.runOnUiThread(Runnable) ▸Runs the specified action on the UI thread. ▸If the current thread is the UI thread, then the action is executed immediately. ▸If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.
  • 56. 56 Example private void runThread() { new Thread() { public void run() { while (i++ < 1000) { runOnUiThread(new Runnable() { @Override public void run() { btn.setText("#" + i); } }); Thread.sleep(300); } } }.start(); }
  • 57. 57 private void runThread() { new Thread() { public void run() { while (i++ < 1000) { try { runOnUiThread(new Runnable() { @Override public void run() { btn.setText("#" + i); } }); Thread.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); }
  • 59. 59 Worker or Background threads ▹View.post (Runnable) ▸Causes the Runnable to be added to the message queue. ▸The runnable will be run on the user interface thread.
  • 60. 60 Example Runnable mSetEditText = new Runnable() { @Override public void run() { } }; new Thread(mSetEditText ).start();
  • 61. 61 new Thread(mSetEditText).start(); Runnable mSetEditText = new Runnable() { int i = 0; @Override public void run() { while (i < 1000000) { i++; } et_text.post(new Runnable() { @Override public void run() { // TODO Auto-generated method stub et_text.setText("i:" + i); } }); } };
  • 63. 63 Worker or Background threads ▹View.postDelayed(Runnable) ▸Causes the Runnable to be added to the message queue, ▸to be run after the specified amount of time elapses ▸The runnable will be run on the user interface thread.
  • 64. 64 Example Handler mHandler; mHandler =new Handler(); Runnable mSetEditText = new Runnable() { @Override public void run() { et_text.setText(“Delayed”); } };
  • 65. 65 Handler mHandler; mHandler =new Handler(); Runnable mSetEditText = new Runnable() { @Override public void run() { et_text.setText(“Delayed”); } }; btt_set_text_delayed.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub mHandler.postDelayed(mSetEditText , 2000); } });
  • 67. 67 Worker or Background threads: Using AsyncTask ▹This kind of code can get complicated and difficult to maintain ▹AsyncTask allows you to perform asynchronous work on your user interface. ▹It performs the blocking operations in a worker thread and then publishes the results on the UI thread, without requiring you to handle threads and/or handlers yourself.
  • 68. 68 Worker or Background threads: Using AsyncTask ▹AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. ▹AsyncTasks should ideally be used for short operations (a few seconds at the most.) ▹If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.
  • 69. 69 Worker or Background threads: Using AsyncTask ▹An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread.
  • 70. 70 Worker or Background threads: Using AsyncTask ▹Params, ▹the type of the parameters sent to the task upon execution. ▹Progress, ▹the type of the progress units published during the background computation ▹Result, ▹the type of the result of the background computation. ▹An asynchronous task is defined by 3 generic types, called • Params, • Progress • Result
  • 71. 71 Worker or Background threads: Using AsyncTask ▹4 steps, called ▸onPreExecute ▸doInBackground ▸onProgreeUpdate ▸onPostExecute
  • 72. 72 Worker or Background threads: Using AsyncTask ▹onPreExecute ▸invoked on the UI thread before the task is executed. ▸This step is normally used to setup the task, for instance by showing a progress bar in the user interface. ▸Runs on the UI thread before doInBackground(Params...)
  • 73. 73 Worker or Background threads: Using AsyncTask ▹doInBackground ▸invoked on the background thread immediately after onPreExecute() finishes executing ▸This method will be executed on the background Thread, so place your long-running code here, don’t attempt to interact with UI objects within this handler. ▸It takes a set of parameter of the type defined in your class implementation ▸You can use the publishProgress() method from within this handler to pass parameter values to the onProgressUpdate() handler, ▸and when your background task is complete, you can return the final result as a parameter to the onPostExecute() handler, which can update the UI accordingly.
  • 74. 74 Worker or Background threads: Using AsyncTask ▹onProgreeUpdate ▸Override this handler to update the UI with interim progress updates. ▸This handler receives the set of parameters passed in to ▸publishProgress (typically within the doInBackground handler). ▸This handler is synchronized with the GUI Thread when executed, so you can safely modify UI elements.
  • 75. 75 Worker or Background threads: Using AsyncTask ▹onPostExecute ▸When doInBackground() has completed, the return value from that method is passed in to this event handler. ▸Use this handler to update the UI when your asynchronous task has completed. ▸This handler is synchronized with the GUI Thread when executed, so you can safely modify UI elements.
  • 76. 76 private class DownloadFilesTask extends AsyncTask<Params, Progress, Result> { protected void onPreExecute() { // Runs on the UI thread before doInBackground() } protected Long doInBackground(Params... urls) { // Perform an operation on a background thread doSomethingLongRunning(); return something; } protected void onProgressUpdate(Progress... progress) { // Runs on UI thread after publishProgress(Progress...) is invoked // from doInBackground() pb.setProgress(progress[0])); } protected void onPostExecute(Result result) { // Runs on the UI thread after doInBackground() showDialog("Downloaded " + result + " bytes"); } }
  • 77. 77 Example params progress result private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { @Override protected void onPreExecute() { // TODO Auto-generated method stub tv_status.setText(“Start downloading"); } . . . }
  • 78. 78 Example params progress result private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { protected Long doInBackground(URL... urls) { Looping { DownloadPicture(); publishProgress((int)howManyHasDownloaded)); } return totalNumberOfPic; } protected void onProgressUpdate(Integer... progress) { tv_status.setText(“Downloading: ”+progress[0])); } protected void onPostExecute(Long result) { tv_status.setText(“Downloaded " + result + " pic"); } }
  • 79. 79 Example private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> { protected Long doInBackground(URL... urls) { int count = urls.length; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += Downloader.downloadFile(urls[i]); publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is called if (isCancelled()) break; } return totalSize; } protected void onProgressUpdate(Integer... progress) { tv_status.setText(progress[0])); } protected void onPostExecute(Long result) { showDialog("Downloaded " + result + " bytes"); } }
  • 80. 80 Worker or Background threads: AsyncTask ▹AsyncTask is not bonded to the activity life cycle ▹The virtual machine will hold on the activity object as long as the AsyncTask is running ▹AsyncTask is running even the activity is destroyed ▹Thus there is a chance multiple AsyncTask is running in the same time ▸Portrait ▸Landscape ▹Not suitable for the long running operation (>few seconds) ▹Use service instead Activity Async Task
  • 82. 82 Introduction ▹Android maintains a MessageQueue (message loop) on the main thread which basically contains a list of Messages or Runnables (set of executable code) that the Looper dispatches to appropriate Handlers. ▹When a process is created for your application, its main thread is dedicated to running a message queue that takes care of managing the top-level application objects (activities, broadcast receivers, etc) and any windows they create. ▹You can create your own threads, and communicate back with the main application thread through a Handler. This is done by calling the same post or sendMessage methods, but from your new thread. ▹The given Runnable or Message will then be scheduled in the Handler's message queue and processed when appropriate.
  • 83. 83 Message Queue Looper, Handler, Message Queue message message message message Looper message Looper message Handler Looper message Looper contain message and associated with the Message Queue. So it could be run into the thread Handler contain looper Handler determine when it should dispatch the message into the message queue and execute them as they come out of the message queue. postAtTime(Runnable, long)…
  • 84. 84 Handler ▹A Handler allows you 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. ▹When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
  • 85. 85 Handler ▹There are two main uses for a Handler: ▸(1) to schedule messages and runnables to be executed as some point in the future; and ▸(2) to enqueue/add an action to be performed on a different thread than your own.
  • 86. 86 Handler ▹When posting or sending to a Handler, you can either allow the item to be processed as soon as the message queue is ready to do so, or specify a delay before it gets processed or absolute time for it to be processed. ▸post(Runnable) ▸postAtTime(Runnable, long) ▸postDelayed(Runnable, long) ▸Handler.post...
  • 87. 87 MessageQueue ▹Low-level class holding the list of messages to be dispatched by a Looper to the Handlers. ▹Messages are not added directly to a MessageQueue, but rather through Handler objects associated with the Looper. ▹MessageQueue (message loop) on the main thread which basically contains a list of Messages or Runnables (set of executable code) that the Looper dispatches to appropriate Handlers.
  • 88. 88 Looper ▹Class used to run a message loop for a thread. ▹The main thread is a message loop and has a looper. ▹Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped. ▹Most interaction with a message loop is through the Handler class.
  • 89. 89 Example class LooperThread extends Thread { public Handler mHandler; public void run() { Looper.prepare(); mHandler = new Handler() { public void handleMessage(Message msg) { // process incoming messages here } }; Looper.loop(); } }
  • 91. 91 Handler, Looper, Runnable ▹More information ▸http://codetheory.in/android-handlers-runnables- loopers-messagequeue-handlerthread/ ▸http://developer.android.com/reference/android/os/H andler.html
  • 92. 92 Reminder ▹Mobile App Development Project