Android 2.1:同时为下载文件运行多个asynctask

时间:2012-12-05 09:50:04

标签: android android-asynctask

我创建了一个asynctask类,可以从网上下载文件。

这是我的班级:

private class DownloadFile1 extends AsyncTask<String, Integer, String> {

    private boolean done = false;
    @Override
    protected String doInBackground(String... sUrl) {
        done = false;
        if (isOnline() == true && sdmounted() == true) {
            try {
                URL url = new URL(sUrl[0]);  // get url
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                InputStream in = new BufferedInputStream(connection.getInputStream());
                // url[1]= file name
                OutputStream out = (downloaded == 0) ? new FileOutputStream("/sdcard/Points.ir/" + sUrl[1])
                        : new FileOutputStream("/sdcard/Points.ir/"
                                + sUrl[1], true);
                OutputStream output = new BufferedOutputStream(out, 1024);
                byte[] data = new byte[1024];
                int count = 0;

                while (done != true && isOnline() == true && (count = in.read(data, 0, 1024)) >= 0) {
                    output.write(data, 0, count);
                    downloaded += count;
                }
                output.flush();
                output.close();
                in.close();
            } catch (Exception e) {
            }
        } else {
            networkerror = 1;
        }
        return null;
    }

    @Override
    protected void onPreExecute() 
    {
        super.onPreExecute();

    }

    @Override
    protected void onProgressUpdate(Integer... progress)
     {
        super.onProgressUpdate(progress);

    }

    @Override
    protected void onPostExecute(String result) 
    {
        super.onPostExecute(result);

    }
}

当我创建这个类的对象和Execute时,每个东西都可以正常工作。但是当同时创建2个对象和Execute for download 2文件时它会得到FC ?? 我该怎么办? (抱歉我的英语口语不好)

1 个答案:

答案 0 :(得分:1)

AsyncTask只能执行一次。因此,一旦您的AsyncTask运行,您就无法再次运行它。这就是你在doInBackground方法中拥有String ... param的原因,它可以是一个字符串列表。

因此,您可以使用以下内容代替创建两个对象:

DownloadFile1 task = new DownloadFile1();
task.execute("url1", "url2", "url3");   // All these urls will be processed after each other

在您的AsyncTask doInBackground()中,您可以执行以下操作:

@Override
protected String doInBackground(String... sUrl) {
    done = false;

    for(int i=0 ; i < sUrl.length ; i++){
        if (isOnline() == true && sdmounted() == true) {
            try {

                String currentUrl = sUrl[i];

                // continue with your code here, using currentUrl instead
                // of using sUrl[0];
            }
        }
    }

}