Friday, September 23, 2011

Android Threads, Handlers and AsyncTask - Tutorial



Threads

Android supports standard Java Threads . You can use standard Threads and the
 tools from the package "java.util.concurrent" to put actions into the background.
 The only limitation is that you cannot directly update the UI from the a 
background process. See Java Concurrency Tutorial for an introduction into 
background processing with standard Java.

If you need to update the UI from a background task you need to use some Android 
specific classes. You can use the class "android.os.Handler" for this or the class
 "AsynTasks". 




AsyncTask

The class AsyncTask encapsulates the creation of Threads and Handlers. 
You must implement the method "doInBackground()", which defines what action
 should be done in the background. This method is be automatically run in a 
separate Thread. To update the UI you can override the method "onPostExecute()". 
This method will be called by the framework once your action is done and runs
within the UI thread. AsynTask

To use AsyncTask you must subclass it. AsynTask uses generics and varargs.
The parameters are the following AsyncTask  . TypeOfVarArgParams is passed into the doInBackground(),
 ProgressValueis used for progress information and ResultValue must be returned
from doInBackground() and is passed to onPostExecute() as parameter. 




Android AsyncTask Example

Today I was working on a loading screen for an Android app. 
The purpose of the loading screen is to report to the user which boot up 
processes were happening as well as provide a nice looking intro screen 
for the app. The U.I. layer of an Android app runs in a single thread.
 You can think of a thread as a stack of function calls. Each function 
in the list executes only after the one before it has completed. 
This is a very simplistic view of a thread but for the sake of this post 
it will work. With multiple processor intensive functions stacked up the U.I.
 layer can become inactive and appear to hang while waiting for the stack to
 finish. This problem can be solved by splitting up the processes into
 separate threads. By doing so your U.I. layer can update concurrent with the
 other more intensive processes.

The Android operating system provides a couple of solutions to this problem.
 The solution I implemented for the loading screen was a class called AsyncTask
. It’s a wrapper for a threaded operation that provides some really convenient
 callbacks for updating progress information and handling task completion.


Link Download

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.