請考慮以下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