如何在方法中实现“下载文件”?

时间:2013-08-08 18:59:21

标签: android android-asynctask download countdownlatch

我创建了一个代码来下载显示进度条进度的多个文件。这很好用,但现在我想把它部署到一个外部项目(库本身),我有问题。

我的目的是调用“下载”,当下载完成或返回0或1.但是异步时方法会在完成之前返回值。我尝试用“CountdownLatch”控制它但没有成功... 有什么想法吗?

以下代码有效,问题是方法“download”返回值而不等待它完成剩下的代码。

Main.java

if(MyLib.download(Main.this, url, nameFiles, "internal", "folderExtra") == 1){
            System.out.println("SUCCESS DOWNLOAD!");
}else{
            System.out.println("error download");
}

MyLib.java

/** DOWNLOADER WITH PROCESSDIALOG **/
    ProgressDialog pDialog;
    Context context;
    String urlName; 
    String[] filesToDownload;
    int downloadOK = -1;
    int currentFile = -1;
    int totalFiles = 0;
    String typeStorage = "internal";
    String folder = "";
    CountDownLatch controlLatch;
    public int download(Context ctx, String urlName, String[] filesToDownload, String typeStorage, String extraFolder ){

            System.out.println("estoy en download");
            this.context = ctx;
            this.urlName = urlName;
            this.filesToDownload = filesToDownload;
            this.totalFiles = filesToDownload.length;
            this.typeStorage = typeStorage;

            /** Almacenamiento de la descarga - Interno o externo **/
            if (typeStorage.equalsIgnoreCase("internal")) {
                System.out.println("internal");
                this.folder = context.getFilesDir().toString() + "/";
            } else if (typeStorage.equalsIgnoreCase("external")) {
                System.out.println("external");
            }

            /** COMPLETEMENTO DIRECTORIO/S OPCIONAL **/
            if (extraFolder != null && extraFolder != "") {
                folder += extraFolder;
            }

            System.out.println("FOLDER: " + folder);
            File directoryFile = new File(folder);
            if (!directoryFile.isDirectory()) {
                if (!directoryFile.mkdir()) {
                    Toast.makeText(context, "No se puede crear el directorio o no existe", Toast.LENGTH_LONG).show();
                }
            }
            pDialog = new ProgressDialog(context);
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setTitle("Descargando recursos...");

            // controlLatch = new CountDownLatch(1);

            startDownload();
            /* 
            try {
                System.out.println("STOP");
                controlLatch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            */          
        return downloadOK;
    }
private void startDownload() {
    currentFile++;
    System.out.println("startDownload!");
    if (currentFile < totalFiles) {
        pDialog.setMessage("Descargando " + (currentFile + 1) + " de " + totalFiles + "\n\n(..." + filesToDownload[currentFile] + ")");
        System.out.println("startDownload currentFile +[" + currentFile + "] totalFiles [" + totalFiles + "]");
        System.out.println("file: " + filesToDownload[currentFile].toString());
        new DownloaderFile().execute(filesToDownload[currentFile]);
    }
}

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

    @Override
    protected String doInBackground(String... params) {
        try {
            File checkFile = new File(folder + params[0]);
            if(!checkFile.exists()){
                URL urlFinal = new URL(urlName+params[0]);
                URLConnection connection = urlFinal.openConnection();
                connection.connect();
                int fileLength = connection.getContentLength();

                InputStream input = new BufferedInputStream(urlFinal.openStream());
                OutputStream output = new FileOutputStream(folder + params[0]);

                byte data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    publishProgress((int) (total * 100 / fileLength));
                    output.write(data, 0, count);
                }
                output.flush();
                output.close();
                input.close();
            } else {
                System.out.println("The file " + filesToDownload[currentFile] + " is downloaded"  );
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "ok";

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        System.out.println("-1");
        File checkFile = new File(folder + filesToDownload[currentFile]);
        if(!checkFile.exists()){
            System.out.println("pDialogShow");
            pDialog.show();
        }
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        super.onProgressUpdate(progress);
        pDialog.setProgress(progress[0]);
    }

    @Override
    protected void onPostExecute(String res) {
        System.out.println("10");
        if (currentFile == (totalFiles - 1)) {
            System.out.println("FINISH!!!!!!!!!!!!!!");
            currentFile = 0;
            pDialog.dismiss();
            downloadOK = 1;
            //controlLatch.countDown();

        } else {
            if (res.equals("ok")) {
                startDownload();
            } else {
                System.out.println("error download");
                downloadOK = 0;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

听起来你想要回电。

您的DownloaderFile类可以使用一个侦听器接口,该接口由包含DownloaderFile对象的任何内容实现。在onPostExecute()内调用该侦听器。

可能看起来像这样:

public class MyActivity extends Activity implements OnDownloadCompleteListener {
    private void startDownload() {
        //inside whatever method        
        Downloader downloader = new Downloader(this); //'this' implements OnDownloadCompleteListener
        downloader.go();
    }

    @Override 
    public void onDownloadFinished(boolean success) {
        //implementation 

    }
}

内部Downloader

//...
@Override
protected void onPostExecute(String res) {
    onDownloadCompleteListener.onDownloadComplete(true);
}

OnDownloadCompleteListener接口:

public interface OnDownloadCompleteListener {
    public void onDownloadComplete(boolean success);
}