In Android development, AsyncTask is a class that was traditionally used to perform background operations and update the user interface without having to manipulate threads and/or handlers. Although AsyncTask has been deprecated in Android 11, understanding how to integrate it with other Android components can still be valuable for maintaining legacy applications. This guide provides a simple example of using AsyncTask with an Activity.
Here's a simple example of how to use AsyncTask in an Android Activity to fetch data in the background and update the UI:
public class MainActivity extends AppCompatActivity {
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
new FetchDataTask().execute("https://api.example.com/data");
}
private class FetchDataTask extends AsyncTask {
@Override
protected String doInBackground(String... urls) {
String result = "";
// Simulate a network operation
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
result = stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(String result) {
// Update the UI with the fetched data
textView.setText(result);
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?