Download - Thread Handling in Android
5/10/2018 Thread Handling in Android - slidepdf.com
http://slidepdf.com/reader/full/thread-handling-in-android 1/14
Xoriant Software Product Engineering Blog
Product Engineering Outsourcing, Tech Talk
Home
About
Sidebar Off
Categories
Android
Cloud Computing for ISVs
CSR
GUI: Flash, Flex, Ajax, Silverlight
Mobile Application Development
Product Ideation
Software Product DevelopmentSoftware Testing and QA
Web 2.0 / Social Networking
Archives
August 2011
July 2011
June 2011
May 2011
April 2011
January 2011
December 2010November 2010
October 2010
September 2010
August 2010
July 2010
June 2010
February 2010
December 2009
November 2009
October 2009
February 2009
January 2009
December 2008
15
Jul
Android Async Task http://www.xoriant.com/blog/mobile-applicatio
1 of 14 Tuesday 30 August 2011 03
5/10/2018 Thread Handling in Android - slidepdf.com
http://slidepdf.com/reader/full/thread-handling-in-android 2/14
Android Async Task
ReplyAndroid, Mobile Application Development July 15th, 2010Prashant Thakkar
This blog post introduces one of the important mechanism of Async Task for
Android with sample code.
Android implements single thread model and whenever an Android application is
launched, a thread is created. Now assume you have long running operations
like a network call on a button click in your application. On button click a
request would be made to the server and response will be awaited. Now due to
the single thread model of Android, till the time response is awaited your UI
screen hangs or in other words, it is non-responsive.
We can overcome this by creating a new Thread and implement the run method
to perform the time consuming operation, so that the UI remains responsive.
As shown below a new Thread is created in onClick method
But since Android follows single thread model and Android UI toolkit is not
thread safe, so if there is a need to make some change to the UI based on theresult of the operation performed, then this approach may lead some issues.
There are various approaches via which control can be given back to UI thread
(Main thread running the application). Handler approach is one among the
various approaches.
Handler
Let us look at the code snippet below to understand Handler approach.
12345678
public void onClick(View v) {Thread t = new Thread(){public void run(){
// Long running operation}};t.start();
}
?
Android Async Task http://www.xoriant.com/blog/mobile-applicatio
2 of 14 Tuesday 30 August 2011 03
5/10/2018 Thread Handling in Android - slidepdf.com
http://slidepdf.com/reader/full/thread-handling-in-android 3/14
As seen we have modified the original run method and added code to create
Message object, which is then passed as parameter to sendMessage method of
Handler. Now let us look at the Handler. Note that the code below is present
in the main activity code.
After the execution of long running operation, the result is set in Message and
passed to sendMessage of handler. Handle will extract the response from
Message and will process and accordingly update the UI. Since Handler is part
of main activity, UI thread will be responsible for updating the UI.
Handler approach works fine, but with increasing number of long operations,
Thread needs to be created, run method needs to be implemented and Handler
needs to be created. This can be a bit cumbersome. The Android framework has
identified this pattern and has nicely enveloped it into what is called an Android
Async Task . Let us look at how it can help simplify things.
Async Task
Android Async Task takes cares of thread management and is the recommended
mechanism for performing long running operations.
Let us look at a sample class LongOperation, which extends the AsyncTask
below:
01020304050607
080910111213
public void onClick(View v) {Thread t = new Thread(){public void run(){
// Long time comsuming operationMessage myMessage=new Message();Bundle resBundle = new Bundle();resBundle.putString("status", "SUCCESS");
myMessage.obj=resBundle;handler.sendMessage(myMessage);
}};t.start();
}
123456
private Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {// Code to process the response and update UI.
}};
?
?
Android Async Task http://www.xoriant.com/blog/mobile-applicatio
3 of 14 Tuesday 30 August 2011 03
5/10/2018 Thread Handling in Android - slidepdf.com
http://slidepdf.com/reader/full/thread-handling-in-android 4/14
Modify the onClick method as shown below:
As seen class LongOperation extends AsyncTask and implements 4 methods:
doInBackground: Code performing long running operation goes in this
method. When onClick method is executed on click of button, it callsexecute method which accepts parameters and automatically calls
doInBackground method with the parameters passed.
1.
onPostExecute: This method is called after doInBackground method
completes processing. Result from doInBackground is passed to this
method.
2.
onPreExecute: This method is called before doInBackground method is
called.
3.
01020304050607
080910111213141516171819
202122232425262728293031
32
private class LongOperation extends AsyncTask<String, Void, Strin
@Overrideprotected String doInBackground(String... params) {// perform long running operation operationreturn null;
}
/* (non-Javadoc)* @see android.os.AsyncTask#onPostExecute(java.lang.Object)*/@Overrideprotected void onPostExecute(String result) {// execution of result of Long time consuming operation
} /* (non-Javadoc)* @see android.os.AsyncTask#onPreExecute()*/
@Overrideprotected void onPreExecute() {// Things to be done before execution of long running operation.}
/* (non-Javadoc)* @see android.os.AsyncTask#onProgressUpdate(Progress[])*/@Overrideprotected void onProgressUpdate(Void... values) {
// Things to be done while execution of long running operat}
}
123
public void onClick(View v) {new LongOperation().execute("");}
?
?
Android Async Task http://www.xoriant.com/blog/mobile-applicatio
4 of 14 Tuesday 30 August 2011 03
5/10/2018 Thread Handling in Android - slidepdf.com
http://slidepdf.com/reader/full/thread-handling-in-android 5/14
onProgressUpdate: This method is invoked by calling publishProgress
anytime from doInBackground call this method.
4.
Overriding onPostExecute, onPreExecute and onProgressUpdate is optional.
Points to remember:
Instance of Async Task needs to be created in UI thread. As shown in
onClick method a new instance of LongOperation is created there. Also
execute method with parameters should be called from UI thread.
1.
Methods onPostExecute, onPreExecute and onProgressUpdate should not
be explicitly called.
2.
Task can be executed only once.3.
Hope this blog helped you understand Android async task and why it is
important in Android application development.
Prashant Thakkar – Team member – Xoriant Mobile Center of Excellence.
Like 13 likes. Sign Up to see what your friends like.
Related posts:
Android Menus An application menu is critical to any mobile application. This is becausereal estate in a mobile device is limited, so the developer has to make judicious use of menus...
1.
Android – UI Design Guidelines The user interface plays one of the most important
roles in determining how successfully you can attract and retain the users by making the UI
easy to use, efficient and...
2.
This entry was posted on Jul 15th, 2010 at 3:49 am and is filed under Android, Mobile Application
Development.You can follow any responses to this entry through the RSS 2.0. You can Leave a
response, or Trackback .
27 Responses to “Android Async Task”
praveen
August 7, 2010 at 5:51 pm
Thank you a lot Prashant. It is very useful.
Android Async Task http://www.xoriant.com/blog/mobile-applicatio
5 of 14 Tuesday 30 August 2011 03
5/10/2018 Thread Handling in Android - slidepdf.com
http://slidepdf.com/reader/full/thread-handling-in-android 6/14
Fredrik
August 17, 2010 at 10:09 am
Great, worked like a charm!
Lonnie VanZandt
August 29, 2010 at 5:30 pm
Prashant, this pattern appears adequate for run-to-completion asynchronous
operations. What is the recommended Android pattern for asynchronous
operations which periodically or sporadically repeat?
For example, what is the recommended approach for a background job (not
wanting to lead an answer by using “task” or “service”) which wakes up,checks query parameters, prepares a web service query, executes the query,
marshals query results, posts a notification to observers, and goes to sleep
for some short while. When it awakes, it repeats the “job”. It does this over
and over until instructed to cancel itself.
Tilsan
August 31, 2010 at 7:04 am
This is a Nice Article. Keep up ur good Work !!!!!!!!!!
Prashant Thakkar
September 1, 2010 at 1:32 am
Hi Lonnie,
As per my understanding for the kind of tasks (Job) that you want toperform, writing a service would be an better approach. Service runs in the
background for indefinite period of time and it is possible to control and
access the service via the exposed interface.
Yadavendra
September 18, 2010 at 5:20 am
Android Async Task http://www.xoriant.com/blog/mobile-applicatio
6 of 14 Tuesday 30 August 2011 03
5/10/2018 Thread Handling in Android - slidepdf.com
http://slidepdf.com/reader/full/thread-handling-in-android 7/14
Thanks a lot .This is very helpful
Matze
September 23, 2010 at 8:04 am
Hey Prashant,
does “Task can be executed only once” mean it can only be executed once
and than again if the task has finished or it can not be executed ever again?
=)
Might sound a little weird but I don’t need to call it serveral times over and
over again, so it should be executed before I call it again.
MatzeSeptember 23, 2010 at 8:09 am
Oh, thx for your tutorial by the way, it’s really good =)
Ron
October 3, 2010 at 3:28 am
Hi very useful BUT..
where you have called new LongOperation().execute(“”) I am calling new
CameraTask().execute() and getting an error ‘cannot be resolved to a type’.
I have the Async import at the top of the file. I also received an error re
‘private class CameraTask extends AsyncTask’ in that only abstract or final
are permitted. I am hoping someone can shed some light on this.
Thanks
Ron
October 3, 2010 at 3:32 am
hi found misplaced } which fixed it!
Vijay
November 29, 2010 at 4:19 am
Android Async Task http://www.xoriant.com/blog/mobile-applicatio
7 of 14 Tuesday 30 August 2011 03
5/10/2018 Thread Handling in Android - slidepdf.com
http://slidepdf.com/reader/full/thread-handling-in-android 8/14
Hi, thanks for the good tutorial. How do we get back the result to the calling
UI thread.
Prashant Thakkar
November 29, 2010 at 5:08 am
AsyncTask is either written as anonymous inner classes i.e. within the
method or as a private inner class in the same class file. So UI component to
be modified can be accessed by declaring the it as global variable.
Example:private void doSomething() {
new AsyncTask<String, Void, String>(){
@Override
protected void onPostExecute(String result) {
if (result != null && result.trim().length() == 0){
textView.setText(result);
}else{
textView.setText("Empty Input Parameter");
}
}
@Overrideprotected String doInBackground(String… param){
return param;
}
}.execute("value1");
}
Thanks
Prashant Thakkar
Dattatraya
February 1, 2011 at 12:52 am
Hi Prashant,
The code the return type of the doInBackground() is String. But i want to
load the images from url in background. it is possible…..
Android Async Task http://www.xoriant.com/blog/mobile-applicatio
8 of 14 Tuesday 30 August 2011 03
5/10/2018 Thread Handling in Android - slidepdf.com
http://slidepdf.com/reader/full/thread-handling-in-android 9/14
Thanks in advanced.
Prashant Thakkar
February 1, 2011 at 2:44 am
Yeah it possible to fetch image from server.
You can perform any operation in doInBackground() and accordingly return
string based on whether operation completed successfully or not. For
example
@Override
protected String doInBackground(String… params) {
try{// fetching image
return success;
}catch(Exception e){
return failed;
}
}
The String returned via doInBackground() is available as input parameter
for onPostExecute(String result) method.
ThanksPrashant Thakkar
P
February 5, 2011 at 5:29 pm
The problem with this basic approach is that if something causes the
activity instance to be destroyed (like a screen orientation change) while
your async task is performing its background processing, then by the time
the onPostExecute() method is invoked, back on the UI thread, you will bereferencing the old (dead) Activity instance. This leads to the ‘Leaked
Window’ error message amongst other things, same goes for
onProgressUpdate().
Mukund
March 4, 2011 at 5:24 am
Android Async Task http://www.xoriant.com/blog/mobile-applicatio
9 of 14 Tuesday 30 August 2011 03
5/10/2018 Thread Handling in Android - slidepdf.com
http://slidepdf.com/reader/full/thread-handling-in-android 10/14
All,
Is it necessary to create a service only to perform a recurring task…?
How about having a Handler…?I shall invoke sendMessageAtTime(Message, long) instead of
dispatchMessage(Message).
In handleMessage(Message), I will call the sendMessageAtTime(Message,
long) method, which is nothing but the recurring.
Mukund
March 4, 2011 at 5:27 am
All,
Is it necessary to create a service everytime for a recurring task?
How about using a Handler instead?
I shall call invoke method sendMessageAtTime(Message, long) for the
purpose.
Jason Mayor
March 21, 2011 at 4:03 am
Hi,
I am continuosly getting “This task has already been executed. A task can
be executed only once.” I want to cancel the current running task and start
a new one upon request.
Please suggest,
Json
Dattatraya
April 18, 2011 at 2:18 am
Hi Prashant,
Android Async Task http://www.xoriant.com/blog/mobile-applicatio
10 of 14 Tuesday 30 August 2011 03
5/10/2018 Thread Handling in Android - slidepdf.com
http://slidepdf.com/reader/full/thread-handling-in-android 11/14
I am new in android, i read your blog post regularly. Now I am facing one
problem, it may not related to AsyncTask, but I hope you help me. I am
doing on web base Android Application. I that one view is contain category
in table layout. when we click on any category I get the id of that category,
pass it in URL, send the request to server, get XML, Parse this XML(XML
contain thumb nail image and description), and display that information in
table layout exactly belove the selected category. In my case there are manyrecord(more than 50) so it take 1-2 minute to display thumbnail images on
table layout. I want to show the dialog box while loading and drawing the
thumbnail.
I am trying as u mentioned above. but I am not able to show dialog box at
write time and write place. It display the dialog box after displaying all
thumbnail(may be the boolean return type of On Click).
Please Give me some solution on it. If u want i will give u my source code
also.
Thanks in advance.
khangaiMay 5, 2011 at 4:10 am
thanks. it help me lot
Jay
May 11, 2011 at 7:18 am
Thabk so much!! Very helpful!!!
Vika
June 10, 2011 at 1:56 am
I’d like to show ProgressDialog when the data is passing from database to
2nd spinner.
But something wrong in my code. Could you help me, please?
Spinner marke = (Spinner) findViewById(R.id.spinner1);
marke.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView adapter, View view, int pos, long
id) {
new Background().execute(null);//some code
Android Async Task http://www.xoriant.com/blog/mobile-applicatio
11 of 14 Tuesday 30 August 2011 03
5/10/2018 Thread Handling in Android - slidepdf.com
http://slidepdf.com/reader/full/thread-handling-in-android 12/14
public class Background extends AsyncTask {
@Override
protected void onPreExecute() {
dialog.show();
dialog.setMessage(“Please, wait!”);
}
protected Void doInBackground(Void… params) {
return null;
}
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (dialog != null) {
dialog.dismiss();
}
}
Chris
June 14, 2011 at 2:03 pm
thanks a lot for this pretty nice article!
pratheeja
June 21, 2011 at 9:47 pm
hi Prashant,
Thank you for ths nice article. It helped me a lot.
Seth Kigen
June 29, 2011 at 10:43 pm
Thanks for this post, it was really helpful.
Saved me a lot.
Nital
July 4, 2011 at 3:06 am
Android Async Task http://www.xoriant.com/blog/mobile-applicatio
12 of 14 Tuesday 30 August 2011 03
5/10/2018 Thread Handling in Android - slidepdf.com
http://slidepdf.com/reader/full/thread-handling-in-android 13/14
Thanks a lot for this post.. very well explained!!!
Jon
July 25, 2011 at 6:49 pm
Thank you for a clear explanation of how to use a nested onpostexecute to
pass values back to the original activity.
Add reply
Name (*)
Mail (will not be published) (*)
Website
Submit(Ctrl+Enter)
Search:
Recent Posts
Know how to develop Widgets for Android Applications with code
snippets
Find Nth maximum record in Database
Android UI Design Pattern – Quick Action Bar
Mobile Application Testing – A Quality Approach Android UI Design Pattern – Action Bar
Recent Comments
Dada Mote on FitNesse- Testing Business scenarios for UAT
Dada Mote on Selenium -Open Source Test Automation: An Overview
RS on Agile – a Win-Win Methodology
Harsh on FitNesse- Testing Business scenarios for UAT
Android Async Task http://www.xoriant.com/blog/mobile-applicatio
13 of 14 Tuesday 30 August 2011 03
5/10/2018 Thread Handling in Android - slidepdf.com
http://slidepdf.com/reader/full/thread-handling-in-android 14/14
Thomas on Selenium -Open Source Test Automation: An Overview
Tags
3D graphic Action Bar Adobe Flash Agile Android Android Application
android application development android apps
Android development Android Layout Android UI Automation Testing Blackberry Cloud cloud computing
cloud management CSS Dashboard design Flex google App Graphics Health
IDE Intuitive user Interface iPhone Mobile application developmentOpen Source Product Maturity QA RIA Ruby on Rails Selenium Silverlight Social
Networking Software Methodology tech talk Testing Twitter UI UI design
pattern Web2.0 Web 2.0 Web App Web Development WebUI
Valid XHTML 1.0 and CSS 3!
Home
About
Xoriant Solutions
Xoriant
Join the conversation
Xoriant launches Enterprise Mobility platform for mobilizing enterprise applications http://t.co/Ix197Uy #mobileapp #framework
5 hours ago · reply · retweet · favorite
How do I select the right outsourcing partner? Find out answers to more such persistent questions while#outsourcing at http://t.co/BpCBBir5 hours ago · reply · retweet · favorite
Blog: Learn about IPv6: The Next Generation Internet Protocol http://t.co/wIbqfIE #IPv65 hours ago · reply · retweet · favorite
Blog:Know how to develop #Widgets for #Android Applications with code snippets #Mobile Applicationhttp://t.co/E8d9yKe5 hours ago · reply · retweet · favorite
Case study:Location aware Android based loyalty #mobile application for local restaurants http://t.co /TVrNMAe #Android #Location based appyesterday · reply · retweet · favorite
Android Async Task http://www.xoriant.com/blog/mobile-applicatio
14 of 14 Tuesday 30 August 2011 03