blog

Home / DeveloperSection / Blogs / Background Processing in Android

Background Processing in Android

Chris Anderson7986 15-Oct-2011

Android modifies the user interface via one Thread, the UI Thread. If the programmer does not use any concurrency constructs all the code of an android application run in this UI thread. If we perform a long running operation, it may block our user interface of android application.

Therefore all slow running operations in an Android application should run in the background, e.g. via some way of concurrency constructs of Java language or the Android framework. Slow running operations are network, file and database access and complex calculations.

In this blog I am going to explain special Android constructs for concurrency in an Android application.

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 background process.

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 AsyncTasks.

Handler

The class Handler can update the UI. A handle provides methods for receiving messages and for runnables. To use a handler you have to subclass it and overidehandleMessage() to process messages. To process runables you can use the method post (); you only need one instance of a handler in your activity.

Your thread can post messages via the method sendMessage (Message msg) or sendEmptyMessage.

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 being 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.


Updated 18-Sep-2014
hi I am software developer at mindstick software pvt. ltd.

Leave Comment

Comments

Liked By