从Internet(AsyncTask)下载图像需要太长时间

时间:2012-09-20 10:51:56

标签: android

我正在使用AsyncTask执行连接互联网,下载数据,然后获取互联网图片的操作。

从互联网上获取的图像,但是当服务器响应应用程序时获得FC。

如何获取数据AsyncTask虽然它需要服务器?

然后我把我用来下载数据的代码:

class CargaImgs extends AsyncTask<Void, Void, Bitmap> {

    final ProgressDialog progressDialog = new ProgressDialog(imagen.this);

    protected void onPreExecute() {
        progressDialog.setTitle("");
        progressDialog.setMessage("Cargando Imagen...");
        progressDialog.show();
    }

    protected Bitmap doInBackground(Void... params) {
        return urlImageToBitmap(imageUrl(StrUrl));
    }

    protected void onPostExecute(Bitmap imagen) {
        RawBmp = imagen;
        sourceBmp = RawBmp;
        sourceBmp = redimensionarImagenMaximo(sourceBmp, screen_w, screen_h);
        imageWidth = sourceBmp.getWidth();
        imageHeight = sourceBmp.getHeight();
        showBmp = Bitmap.createBitmap(sourceBmp);
        main.invalidate();
        primera_carga = false;
        progressDialog.dismiss();
    }
}

private String imageUrl(String url) {
    Document doc = null;
    try {
        doc = Jsoup.connect(url).get();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    Elements div_exterior = doc.getElementsByClass("inner");
    for (Element subelementos : div_exterior) {
        Elements imgs = subelementos.getElementsByTag("img");
        StrUrlImage = imgs.get(1).attr("src");
        if (StrUrlImage == StrUrlImage2) {

        } else {
            return imgs.get(1).attr("src");
        }
    }
    return null;
}

public Bitmap urlImageToBitmap(String urlImage) {
    Bitmap mIcon1 = null;
    URL url_value;
    try {
        url_value = new URL(urlImage);
        if (url_value != null) {
            mIcon1 = BitmapFactory.decodeStream(url_value.openConnection()
                    .getInputStream());
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return mIcon1;
}

1 个答案:

答案 0 :(得分:0)

避免在绘制时使用main.invalidate()(再次绘制整个视图 - 每次执行AsyncTask时) 而是将位图设置为所需视图或仅使该视图无效。

public Bitmap urlImageToBitmap(String urlImage) {
    Bitmap mIcon1 = null;
    URL url_value;
    try {
        url_value = new URL(urlImage);
        if (url_value != null) {

            URLConnection conn = url_value.openConnection();
            conn.setConnectTimeout(10000);

            mIcon1 = BitmapFactory.decodeStream(conn.getInputStream());
        }
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
    }catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return mIcon1;
}

关于postExecute,如果doInBackground中有异常,它将返回null,这可能导致空指针异常。所以在后执行中处理它。