请考虑以下AsyncTask。它旨在从URL下载图像并将其保存到设备,同时通过水平ProgressBar显示进度。现在我根本没有使用变量“位图”(它仍然为空)。有两件事情我希望能够做到:Android - 在显示进度的同时将图像从URL加载到ImageView(不保存图像)
负载从URL中的图像到ImageView的不实际的文件保存到我的设备(?这是甚至可能的),并显示一个进度条,而这样做 - 实际上显示进度,不仅仅是一个动画圈。
(对于知道毕加索的人)用毕加索做同样的事情(http://square.github.io/picasso/)。 毕加索确实使一切都变得简单,我可以使用下面这行代码:
Picasso.with(getApplicationContext()).load(url).into(imageView);
然而,如果我可以真正展示进度(同样使用实际显示进度的ProgressBar),那将会很好。
任何帮助,将不胜感激。此外,我会很感激任何有关当前代码的反馈,以及如何改进(大部分后面跟着这个YouTube教程,所以我觉得我应该给信贷:https://www.youtube.com/watch?v=5HDr9FdGIVg)。
private class ImageDownloadTask extends AsyncTask<String, Integer, Bitmap>{
private int contentLength = -1;
private URL downloadURL = null;
private HttpURLConnection connection = null;
private InputStream inputStream = null;
private File file;
private OutputStream outputStream = null;
private int counter = 0;
private Bitmap bitmap = null;
@Override
protected void onPreExecute()
{
setProgressBarProgress(0);
showProgressBar();
}
@Override
protected Bitmap doInBackground(String[] objects)
{
try
{
downloadURL = new URL(url);
connection = (HttpURLConnection)downloadURL.openConnection();
contentLength = connection.getContentLength();
inputStream = connection.getInputStream();
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/" + Uri.parse(objects[0]).getLastPathSegment());
outputStream = new FileOutputStream(file);
byte buffer[] = new byte[1024];
int read = -1;
while ((read = inputStream.read(buffer)) != -1)
{
outputStream.write(buffer, 0, read);
counter += read;
publishProgress(counter);
};
}
catch (SecurityException e)
{
Msg.log("Security Exception: " + e.getMessage());
}
catch (Exception e)
{
Msg.log("Other Exception: " + e.getMessage());
}
finally
{
//Even if our attempt to download the image did not succeed,
//we should still close the connection, and the streams.
//Otherwise, we are potentially wasting the device's resources.
if (connection!=null)
connection.disconnect();
try {inputStream.close();}
catch (IOException e) {e.printStackTrace();}
try {outputStream.close();}
catch (IOException e) {e.printStackTrace();}
try {outputStream.flush();}
catch (IOException e) {e.printStackTrace();}
}
return bitmap;
}
@Override
protected void onProgressUpdate(Integer... values)
{
int progress = (int)(((double)values[0]/contentLength)*100);
setProgressBarProgress(progress);
}
@Override
protected void onPostExecute(Bitmap result)
{
hideProgressBar();
if (result != null) {
imageView.setImageBitmap(result);
}
}
}
的可能的复制[如何添加进度条到毕加索库(http://stackoverflow.com/questions/32184156/how-to-add-progress-bar-to-毕加索图书馆) – Chisko