Showing posts with label threading. Show all posts
Showing posts with label threading. Show all posts

Tuesday, March 19, 2013

Android AsyncTasks (MultiThreading)

This tutorial explains what AsyncTasks are in Android, why you should use them, and demonstrates a simple app that calculates prime numbers to show them in action.

1. What is an AsyncTask and Why Should I use Them?

AsyncTasks are asynchronous because they operate in a thread separate from the UI thread.

You should use them to complete performance intensive tasks or tasks that may complete in an indefinite amount of time. If you do not, the user interface will be blocked until the task is finished.

For example: if you trying to download a huge web page, if you task is run in the UI thread you will prevent the application from respond to other actions--such as pressing other buttons, zooming, pressing the back button--and your app will be frozen.

No one likes it when an app completely freezes, even if it is doing legitimate loading/calculating work. Additionally, if your app blocks the UI thread for more than 20 or so seconds, the Android Operating System will assume it is broken, and a force-close dialog will appear.