首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >安卓doInBackground

安卓doInBackground
EN

Stack Overflow用户
提问于 2011-04-23 08:19:09
回答 2查看 5.3K关注 0票数 1

大家好,我怎么才能让这段代码一直等到下载完图片

我可以用什么来替换doInBackground(URL... paths),使其等待下载,然后继续执行其余代码

代码语言:javascript
运行
复制
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;

        }
    }
}
EN

Stack Overflow用户

发布于 2011-04-23 09:03:18

关于AsyncTask的要点是您的活动(创建AsyncTask)中的主要代码不需要等待。Async是异步的缩写-这意味着在没有预先确定的时间范围内发生的事情。

如果你想在其他代码执行之前完成一次或多次下载,那么你要么需要以同步的方式执行事情(不适合Android活动),要么你需要编写代码来等待回调。

票数 0
EN
查看全部 2 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5761245

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档