Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何实施";下载程序文件“;用什么方法?_Android_Android Asynctask_Download_Countdownlatch - Fatal编程技术网

Android 如何实施";下载程序文件“;用什么方法?

Android 如何实施";下载程序文件“;用什么方法?,android,android-asynctask,download,countdownlatch,Android,Android Asynctask,Download,Countdownlatch,我创建了一个代码来下载显示progressbar进度的多个文件。这非常有效,但现在我想将其部署到外部项目(库本身),我遇到了一些问题 我的意图是调用“下载”,当下载完成或返回0或1时。但由于异步,该方法在完成之前返回值。我尝试使用“CountdownLatch”控制它,但没有成功。。。 有什么想法吗 以下代码正常工作,问题是方法“download”返回值而不等待它完成其余代码。 Main.java if(MyLib.download(Main.this, url, nameFiles, "int

我创建了一个代码来下载显示progressbar进度的多个文件。这非常有效,但现在我想将其部署到外部项目(库本身),我遇到了一些问题

我的意图是调用“下载”,当下载完成或返回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");
}
/** 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;
            }
        }
    }
}
MyLib.java

if(MyLib.download(Main.this, url, nameFiles, "internal", "folderExtra") == 1){
            System.out.println("SUCCESS DOWNLOAD!");
}else{
            System.out.println("error download");
}
/** 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;
            }
        }
    }
}
/**带PROCESSDIALOG的下载程序**/
ProgressDialog;
语境;
字符串名称;
字符串[]filesToDownload;
int downloadOK=-1;
int currentFile=-1;
int totalFiles=0;
字符串typeStorage=“internal”;
字符串文件夹=”;
倒计时锁存控制;
公共int下载(上下文ctx、字符串urlName、字符串[]文件下载、字符串类型存储、字符串外部文件夹){
System.out.println(“estoy en下载”);
this.context=ctx;
this.urlName=urlName;
this.filesToDownload=filesToDownload;
this.totalFiles=filesToDownload.length;
this.typeStorage=typeStorage;
/**阿拉木图-内部和外部**/
if(typeStorage.equalsIgnoreCase(“内部”)){
系统输出打印项次(“内部”);
this.folder=context.getFilesDir().toString()+“/”;
}else if(typeStorage.equalsIgnoreCase(“外部”)){
系统输出打印项次(“外部”);
}
/**完成董事职务**/
如果(extraFolder!=null&&extraFolder!=“”){
文件夹+=外部文件夹;
}
System.out.println(“文件夹:+文件夹”);
文件目录File=新文件(文件夹);
如果(!directoryFile.isDirectory()){
如果(!directoryFile.mkdir()){
Toast.makeText(上下文,“不存在”,Toast.LENGTH_LONG.show();
}
}
pDialog=新建进度对话框(上下文);
pDialog.setUndeterminate(假);
pDialog.setCancelable(假);
pDialog.setMax(100);
pDialog.setProgressStyle(ProgressDialog.STYLE_水平);
pDialog.setTitle(“描述递归…”);
//controlLatch=新的倒计时锁存器(1);
startDownload();
/* 
试一试{
系统输出打印项次(“停止”);
controlLatch.await();
}捕捉(中断异常e){
e、 printStackTrace();
}
*/          
返回下载OK;
}
私有void startDownload(){
currentFile++;
System.out.println(“startDownload!”);
如果(currentFile
听起来你想要回拨

您的
DownloaderFile
类可以采用一个已实现的侦听器接口
public interface OnDownloadCompleteListener {
    public void onDownloadComplete(boolean success);
}