The abstract class AsyncTask is one of the most popular concurrency tools in Android. It lets you run code in a background thread while still communicating with the user interface. But AsyncTask has a well-known issue: if you declare an AsyncTask object as a member of an Activity, the task can be destroyed along with its parent activity during a configuration change, such as a change in orientation. To prevent this, you can host the asynctask in a fragment object that doesn’t have a user interface. That object can be retained in memory, even during app configuration changes.
- View Offline
- [Voiceover] Mobile applications depend on multithreading…to give the user a sense of good performance.…If you do all of your work on the user interface thread,…the application can freeze up during long-running tasks.…The abstract class "AsyncTask" is one of the most popular…concurrency tools in Android.…It lets you run code in a background thread…while communicating with the user interface.…But AsyncTask has a well known issue.…If you declare an AsyncTask object as a member of…an activity, the task can be destroyed along with its…paired activity during a configuration change,…such as a change in orientation.…
In this project, "AsyncFragment," I've declared…a class that extends AsyncTask.…It has the methods "doInBackground,"…and "onProgressUpdate."…The code "doInBackground" is executed…in the background thread, and "onProgressUpdate"…is executed on the user interface thread…so I can provide information that the user can see.…Whenever I call publishProgress from the…background thread, that data is passed into the…
Watch these Java tutorials to learn smarter, more efficient methods for Android app development.
- Preparing the development environment
- Packaging and running Android apps
- Optimizing Java code for Android
- Implementing event handler interfaces
- Defining custom callback methods
- Working with the Android SDK's Java packages
- Storing data
- Reading text files
- Parsing JSON and XML data
- Managing device sensors
- Playing audio