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.
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.
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 overide handleMessage() 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.
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.