AsyncTask finish execution

1

I would like to know how I could pause, cancel this function once I close the Activity that is running.

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
}
    
asked by anonymous 12.11.2014 / 19:11

1 answer

1

I confess with some shame that I have never tried this in my applications, although it is a functionality that may be considered basic (interrupt an HTTP request), but I believe the following code will work when calling task.cancel() :

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    private ImageView bmImage;
    private InputStream in = null;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            HttpURLConnection conexao = new java.net.URL(urldisplay).openConnection();
            new Thread(new Runnable() {
                @Override
                public void run() {
                   while (in == null && false == isCancelled()) {
                       // Aguarda conexão ser estabelecida e InputStream estar disponível
                   }

                   if (isCancelled()) {
                       conexao.disconnect();
                   }
                }
            }).start();
            in = conexao.getInputStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
}

The solution is not yet complete because the InputStream is not readable in case of a task.cancel() call (although it is possible that it will work anyway if the disconnect() takes the InputStream being read to launch a IOException ), but I do not have time to think about a solution at the moment.

    
12.11.2014 / 20:09