我已經有了ImageView的列表視圖,然後在AsyncTask(適用於我應用程序中任何類型文件的通用下載器)的幫助下開始下載圖像列表。 我需要將每個下載的圖像插入到ImageView後。所以我認爲我需要從我的AsyncTask到主線程的某種回調,但是如何去做它我不知道?從asynctask更新Imageview
這裏是我的AsyncTask代碼
DownloadFileFromURL下來=(DownloadFileFromURL)新DownloadFileFromURL(目的地).execute( 「http://example.com」);
public class DownloadFileFromURL extends AsyncTask<String, String, String> {
private String Destination;
public DownloadFileFromURL(String UrlDestination){
this.Destination=UrlDestination;
}
/**
* Before starting background thread Show Progress Bar Dialog
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Downloading file in background thread
* */
@Override
protected String doInBackground(String... f_url) {
int count;
try {
URL url = new URL(f_url[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a tipical 0-100%
// progress bar
int lenghtOfFile = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),8192);
// Output stream
Log.d("City.xml:",this.Destination);
File targetFile = new File(this.Destination);
File parent = targetFile.getParentFile();
if(!parent.exists() && !parent.mkdirs()){
Log.e("Error: ", ": " + parent);
}
//OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "/"+this.Destination);
OutputStream output = new FileOutputStream(targetFile);
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
}
/**
* After completing background task Dismiss the progress dialog
* **/
@Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
}
}
我用這個DownloadFileFromURL類下載不同的文件,不僅圖像,所以我想將它保存更普遍的,一個不能修改,或將其設置爲特定的ListView – SERG
@SERG I更新了答案。 – Ari