0

可能重复:
使用 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:我的意思是进度条显示完成百分比

4

2 回答 2

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]);
}

}

于 2013-01-31T07:39:40.660 回答
0
  1. 计算所有图像的总大小
  2. 显示进度条并开始下载您的文件,
  3. 下载时更新您的进度,
  4. 只有在所有文件都下载后删除你的酒吧。
于 2013-01-31T07:43:30.757 回答