I am using AsyncTask
to perform some background calculations but I am unable to find a correct way to handle exceptions. Currently I am using the following code:
private class MyTask extends AsyncTask<String, Void, String>
{
private int e = 0;
@Override
protected String doInBackground(String... params)
{
try
{
URL url = new URL("http://www.example.com/");
}
catch (MalformedURLException e)
{
e = 1;
}
// Other code here...
return null;
}
@Override
protected void onPostExecute(String result)
{
if (e == 1)
Log.i("Some Tag", "An error occurred.");
// Perform post processing here...
}
}
I believe that the variable e maye be written/accessed by both the main and worker thread. As I know that onPostExecute()
will only be run after doInBackround()
has finished, can I omit any synchronization?
Is this bad code? Is there an agreed or correct way to handle exceptions in an AsyncTask
?
This class was deprecated in API level 30. AsyncTask was intended to enable proper and easy use of the UI thread. However, the most common use case was for integrating into UI, and that would cause Context leaks, missed callbacks, or crashes on configuration changes.
In summary, the three most common issues with AsyncTask are: Memory leaks. Cancellation of background work. Computational cost.
There are two simple solutions that cover most situations: Either check AsyncTask. isCancelled() on a regular basis during your long-running operation, or keep your Thread interruptible. Either way, when you call AsyncTask. cancel() these methods should prevent your operation from running longer than necessary.
AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
I've been doing that in my apps, I guess there is not a better way.
You can also read Mark Murphy answer about it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With