Junior — Middle
Can you explain what AsyncTask is and how it is used in Android development?
sobes.tech AI
Answer from AI
AsyncTask is a class in Android that allows executing asynchronous operations in the background thread and updating the UI thread after completion. It helps avoid blocking the main thread during long operations, such as data loading from the network.
Main methods of AsyncTask:
doInBackground(Params...)— runs in the background thread, where the main work is written.onPreExecute()— called on the UI thread before starting work.onPostExecute(Result)— called on the UI thread after background work is finished.onProgressUpdate(Progress...)— updates progress on the UI.
Example usage:
private class DownloadTask extends AsyncTask<String, Integer, String> {
protected void onPreExecute() {
// Prepare UI
}
protected String doInBackground(String... urls) {
// Download data
return "result";
}
protected void onPostExecute(String result) {
// Update UI after download
}
}
// Start
new DownloadTask().execute("http://example.com");
Important: starting from Android API 30, AsyncTask is considered deprecated, and it is recommended to use other approaches such as Kotlin Coroutines or WorkManager.