大家好,我怎么才能让这段代码一直等到下载完图片
我可以用什么来替换doInBackground(URL... paths),使其等待下载,然后继续执行其余代码
private class DownloadImageTask extends AsyncTask<URL, Integer, Bitmap> {
    // This class definition states that DownloadImageTask will take String
    // parameters, publish Integer progress updates, and return a Bitmap
    protected Bitmap doInBackground(URL... paths) {
        URL url;
        try {
            url = paths[0];
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            int length = connection.getContentLength();
            InputStream is = (InputStream) url.getContent();
            byte[] imageData = new byte[length];
            int buffersize = (int) Math.ceil(length / (double) 100);
            int downloaded = 0;
            int read;
            while (downloaded < length) {
                if (length < buffersize) {
                    read = is.read(imageData, downloaded, length);
                } else if ((length - downloaded) <= buffersize) {
                    read = is.read(imageData, downloaded, length
                            - downloaded);
                } else {
                    read = is.read(imageData, downloaded, buffersize);
                }
                downloaded += read;
                publishProgress((downloaded * 100) / length);
            }
            Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,
                    length);
            if (bitmap != null) {
                Log.i(TAG, "Bitmap created");
            } else {
                Log.i(TAG, "Bitmap not created");
            }
            is.close();
            return bitmap;
        } catch (MalformedURLException e) {
            Log.e(TAG, "Malformed exception: " + e.toString());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.toString());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.toString());
        }
        return null;
    }
    protected void onPostExecute(Bitmap result) {
        String name = ImageLink.substring(ImageLink
                .lastIndexOf("/") + 1);
        if (result != null) {
            hasExternalStoragePublicPicture(name);
            saveToSDCard(result, name);
            isImage = true;
        } else {
            isImage = false;
        }
    }
}发布于 2011-04-23 09:44:33
doInBackground())在后台执行。waits for the download和continues with the rest of the code的部分是onPostExecute()。这可能就是您所要求的函数。
发布于 2011-04-23 09:03:18
关于AsyncTask的要点是您的活动(创建AsyncTask)中的主要代码不需要等待。Async是异步的缩写-这意味着在没有预先确定的时间范围内发生的事情。
如果你想在其他代码执行之前完成一次或多次下载,那么你要么需要以同步的方式执行事情(不适合Android活动),要么你需要编写代码来等待回调。
https://stackoverflow.com/questions/5761245
复制相似问题