使用 AsyncTask 下载多个文件的问题 [英] Problem with downloading multiple files using AsyncTask

查看:25
本文介绍了使用 AsyncTask 下载多个文件的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用基于教程的以下脚本 Android 系列:下载文件与进度对话框 将多个视频文件从互联网下载到 SD 卡.它会在下载过程中显示一个进度条.

I'm using the following script based on the tutorial Android Series: Download files with Progress Dialog to download multiple video files from the internet to the SD card. It displays a progress bar while the download is in progress.

public class MyDownload extends Activity {

public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
private Button startBtn;
private ProgressDialog mProgressDialog;

private String videoPath = "http://my_site.com/test_videos/";    
private String[] fileNames = {"file1.mp4","file2.mp4"};
private TextView tv;    


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    startBtn = (Button)findViewById(R.id.startBtn);
    startBtn.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
            startDownload();
        }
    });
}

private void startDownload() {      

    tv = (TextView) findViewById(R.id.TextView01);       

    if(checkExternalMedia()==true) {

           File file = null;                
           for(int i=0; i<fileNames.length; i++) {
                file = new File("/sdcard/videos/"+fileNames[i]);
                boolean exists = file.exists();
                if(exists){
                    tv.append("

"+fileNames[i]+" already exists");
                    continue;
                }
                else {
                    new DownloadFileAsync().execute(videoPath+fileNames[i],fileNames[i]);               
                }
                file = null;
            }               
        }            
    else {          
        tv.append("

External Media is NOT readable/writable");
    }
}

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Downloading files...");
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
    }
}

/** Method to check whether external media available and writable. */

private boolean checkExternalMedia(){
    boolean mExternalStorageAvailable = false;
    boolean mExternalStorageWriteable = false;
    boolean stat;
    String state = Environment.getExternalStorageState();

    if (Environment.MEDIA_MOUNTED.equals(state)) {
        // Can read and write the media
        mExternalStorageAvailable = mExternalStorageWriteable = true;
        stat = true;
    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // Can only read the media
        mExternalStorageAvailable = true;
        mExternalStorageWriteable = false;
        stat = false;
    } else {
        // Can't read or write
        mExternalStorageAvailable = mExternalStorageWriteable = false;
        stat = false;
    }          
    tv.append("

External Media: readable="+mExternalStorageAvailable+" writable="+mExternalStorageWriteable);

    return stat;
}

class DownloadFileAsync extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_PROGRESS);
    }

    @Override
    protected String doInBackground(String... aurl) {
        int count;

        try {
            URL url = new URL(aurl[0]);
            URLConnection conexion = url.openConnection();
            conexion.connect();

            File root = android.os.Environment.getExternalStorageDirectory();

            int lenghtOfFile = conexion.getContentLength();
            Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(root.getAbsolutePath() + "/videos/" + aurl[1]);

            byte data[] = new byte[10485760];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress(""+(int)((total*100)/lenghtOfFile));
                output.write(data, 0, count);
            }

            output.flush();
            output.close();
            input.close();          

        } catch (Exception e) {}
        return null;

    }
    protected void onProgressUpdate(String... progress) {
         Log.d("ANDRO_ASYNC",progress[0]);
         mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String unused) {
        dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
        tv.append("

File Download Completed!");
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));            
    }
}

}

当每个视频的大小较小(大约 300KB)时,此代码工作正常.但是当视频大小增加到 7-8 MB 时,应用程序就会崩溃.

This code works fine when the size of each video is less (around 300KB). But when the video size increases to 7-8 MB the application crashes.

但是,如果我尝试下载单个大文件而不是

However, if I try to download a single large file instead of

private String[] fileNames = {"file1.mp4","file2.mp4"};

这段代码工作正常.有什么想法吗?

this code works fine. Any thoughts ?

推荐答案

您正在为每个文件保留 10 MB 的缓冲区

You are reserving a buffer of 10 MB per file

byte data[] = new byte[10485760];

由于内存在 Android 设备上受到限制(想想每个进程 24 - 48MB),您将运行在内存不足的情况下.

As memory is constrained on Android devices (think of 24 - 48MB per process), you will run in out of memory situations.

我怀疑您是否需要这么大的缓冲区 - 尝试将其降低到 1MB 甚至更少,然后重试.

I doubt that you need a this big buffer - try lowering that to 1MB or even less and retry.

这篇关于使用 AsyncTask 下载多个文件的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆