可能重复:
Downloading multiple files one by one using AsyncTask?
我正在尝试下载图像(可能大约20个?)然后将它们保存到缓存中。 如何实现下载进度条?每个图像来自一个单独的链接,如果我实现了一个下载进度条..在我的情况下它会加载下载栏二十次吗?
这是我下载图像并将其保存为缓存的方式:
/**
* Background Async Task to Load all product by making HTTP Request
* */
class downloadMagazine extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading.." + "\n" + "加载中..");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
/**
* getting preview url and then load them
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_magazine, "GET", params);
// Check your log cat for JSON reponse
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// magazines found
// Getting array of magazines
mag = json.getJSONArray(TAG_MAGAZINE);
for (int i = 0; i < mag.length(); i++) {
JSONObject c = mag.getJSONObject(i);
// Storing each json item in variable
String magazineUrl = c.getString(TAG_MAGAZINE_URL);
//String issueName = c.getString(TAG_MAGAZINE_NAME);
urlList.add(magazineUrl);
//issueNameList.add(issueName);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
// Building Parameters
List<NameValuePair> param = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json1 = jParser.makeHttpRequest(urlList.get(pos), "GET", param);
// CHECKING OF JSON RESPONSE
// Log.d("All guide: ", json.toString());
try {
issues = json1.getJSONArray(TAG_ISSUE);
for (int i = 0; i < issues.length(); i++) {
JSONObject c = issues.getJSONObject(i);
String image = c.getString(TAG_IMAGE);
imageList.add(image);
//System.out.println(imageList);
}
// STOP THE LOOP
//break;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
/**
* Updating parsed JSON data into ListView
* */
progressDialog.dismiss();
getBitmap();
buttonsCheck();
}
}
private Bitmap getBitmap() {
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory() + folderName+"/Issues/"+issueNumber);
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
for (int i=0; i<=imageList.size()-1; i++)
{
String image= imageList.get(i);
try
{
String filename = String.valueOf(image.hashCode());
Log.v("TAG FILE :", filename);
File f = new File(cacheDir, filename);
// Is the bitmap in our cache?
Bitmap bitmap = BitmapFactory.decodeFile(f.getPath());
// Download it
try {
bitmap = BitmapFactory.decodeStream(new URL(image)
.openConnection().getInputStream());
// save bitmap to cache for later
writeFile(bitmap, f);
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
Log.v("FILE NOT FOUND", "FILE NOT FOUND");
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
return null;
}
private void writeFile(Bitmap bmp, File f) {
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
} catch (Exception ex) {
}
}
}
PS:我的意思是那些显示完成百分比的进度条
答案 0 :(得分:0)
是,使用AsyncTask并在对话框中显示下载进度:
//将对话框声明为您活动的成员字段 ProgressDialog mProgressDialog;
//在onCreate方法
中实例化它mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("Put here the URL .amr file");
private class DownloadFile extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String... sUrl) {
try {
URL url = new URL(sUrl[0]);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[1024];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
mProgressDialog.setProgress(progress[0]);
}
}
答案 1 :(得分:0)