android - 通过 AsyncTask 下载图像并将其显示在 Imageview 中而不存储在 sdcard 中

标签 android android-asynctask progress-bar

我想通过 AsyncTask 下载图像并在 ImageView 中显示它我可以正常执行,但我也想显示进度用户并执行所有这些操作,而无需将文件存储在 SD 卡中。

这是我到目前为止所做的。

class DownloadFileFromURL extends AsyncTask<String, String, String> {

/**
 * Before starting background thread
 * Show Progress Bar Dialog
 * */
@Override
protected void onPreExecute() {
    super.onPreExecute();
    showDialog(progress_bar_type);
}

/**
 * Downloading file in background thread
 * */
@Override
protected String doInBackground(String... f_url) {
    int count;
    try {
        URL url = new URL(f_url[0]);
        URLConnection conection = url.openConnection();
        conection.connect();
        // getting file length
        int lenghtOfFile = conection.getContentLength();

        // input stream to read file - with 8k buffer
        InputStream input = new BufferedInputStream(url.openStream(), 8192);

        // Output stream to write file
        OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");

        byte data[] = new byte[1024];

        long total = 0;

        while ((count = input.read(data)) != -1) {
            total += count;
            // publishing the progress....
            // After this onProgressUpdate will be called
            publishProgress(""+(int)((total*100)/lenghtOfFile));

            // writing data to file
            output.write(data, 0, count);
        }

        // flushing output
        output.flush();

        // closing streams
        output.close();
        input.close();

    } catch (Exception e) {
        Log.e("Error: ", e.getMessage());
    }

    return null;
}

/**
 * Updating progress bar
 * */
protected void onProgressUpdate(String... progress) {
    // setting progress percentage
    pDialog.setProgress(Integer.parseInt(progress[0]));
}

/**
 * After completing background task
 * Dismiss the progress dialog
 * **/
@Override
protected void onPostExecute(String file_url) {
    // dismiss the dialog after the file was downloaded
    dismissDialog(progress_bar_type);

    // Displaying downloaded image into image view
    // Reading image path from sdcard
    String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
    // setting downloaded into image view
    my_image.setImageDrawable(Drawable.createFromPath(imagePath));
}

}

最佳答案

如果你不想在本地下载图片,你应该使用ByteArrayOutputStream而不是FileOutputStream

这是关键代码:

ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
    total += count;
    publishProgress(""+(int)((total*100)/lenghtOfFile));

    outputStream.write(data, 0, count);
}

//after downloading the image
byte[] imageData = outputStream.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
my_image.setImageBitmap(bitmap);

我没有测试它,但我相信这可以帮助你。

关于android - 通过 AsyncTask 下载图像并将其显示在 Imageview 中而不存储在 sdcard 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38940382/

相关文章:

java - 如何在AsyncTask doInBackground()中使用同步对象?

android - AsyncTask HttpPost 在 3G 上执行失败,但在 Wifi 上运行

java - AsyncTask(update) 仅在应用程序第一次打开时有效,但 5 秒后不会更新

javascript - 没有 APC 的表单中的进度条

android - getArrayLength() 返回一个巨大的数字......

带有 Facebook 登录的 Android WebView

c# - 如何在来自 View 模型的异步 Web 客户端调用中使用进度条

python - 如何使用标签文本和自定义栏颜色自定义 Tkinter.ttk 进度条

android - 在 Android 中使用 webview 显示 html 格式的表格

android - 如何在 Android 的 Youtube API V3 中通过 channel ID 获取 Youtube 直播流?