0

我正在使用 AsyncTask 执行连接到 Internet、下载数据、然后获取 Internet 的图片的操作。

图像也是从互联网获得的,但是当服务器响应时,应用程序会得到一个 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;
}
4

1 回答 1

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,可能会导致空指针异常。所以在执行后处理。

于 2012-09-20T11:05:40.560 回答