开发者

Asynctask Error Handling

开发者 https://www.devze.com 2023-01-15 13:09 出处:网络
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:

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 the开发者_运维问答re an agreed or correct way to handle exceptions in an AsyncTask?


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.


I think your code would to the job but there is already some kind of error handling built into the AsyncTask class.

You can avoid to use an extra variable by using the cancel() method and its handler method onCancelled(). When you call cancel within the doInBackground() method the onCancelled method in the UI thread. Whether you call cancel(true) or cancel(false) depends on your needs.


private class MyTask extends AsyncTask<String, Void, String>
{    
    @Override
    protected NewsItem doInBackground(String... params)
    {
        try
        {
            URL url = new URL("http://www.example.com/");
        }
        catch (MalformedURLException e)
        {
            cancel(false/true);  
        }

        // Other code here...

        return null;
    }

    @Override
    protected void onPostExecute(String result)
    {              
        // Perform successful post processing here...
    }

   @Override
    protected void onCancelled() {
        super.onCancelled();
        // Perform error post processing here...
    }
}


This is guaranteed to work, even on SMP architecture. All the synchronization is done for you. It would however be better to use the return value to do this.

0

精彩评论

暂无评论...
验证码 换一张
取 消