How to download a file and open it at the end of the download?

0

I have an Android application, I'm trying to download a .apk and then open it at the end of the download, follow the code used:

        /**
         * baixando arquivo na background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            String caminhoAtt = "/sdcard/download/bee/bee.apk";
            try {
                URL url = new URL(f_url[0]); //f_url[0] é o endereço do arquivo(testado ta certinho)
                URLConnection conection = url.openConnection();
                conection.connect();

                // Pegando tamanho do arquivo
                int lenghtOfFile = conection.getContentLength(); //aqui retorna -1 não sei porque

                // input stream para ler arquivo - com 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                // deletar o arquivo ja existente
                File file = new File(caminhoAtt);
                file.delete();                

                // Output stream para jogar o arquivo no sdcard
                OutputStream output = new FileOutputStream(caminhoAtt); //aqui ocorre o erro

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // mostrando o progresso....
                    // depois disso o onProgressUpdate vai ser chamado
                    publishProgress(""+(int)((total*100)/lenghtOfFile));

                    // escrevendo os dados para o arquivo
                    output.write(data, 0, count);
                }

                // dando flush no output
                output.flush();

                // fechando as streams
                output.close();
                input.close();

            } catch (Exception e) {
                  util xutil = new util();
                  String cMsg = "*** MENSAGEM DE ERRO *** "+ e.getMessage();
                  xutil.showmessage(MainActivity.this,"O Download falhou.",cMsg.toString() );
                  xutil.SaveErrMensagem( cMsg );
            }

            return null;
        }

This is another part of the code that I have not tried because it does not go over the top:

        /**
         * Atualizando barra de progresso
         * */
        protected void onProgressUpdate(String... progress) {
            // colocando a porcentagem do progresso
            pDialog.setProgress(Integer.parseInt(progress[0]));
       }

        /**
         * Depois de completar a tarefa de fundo
         * fecha o processDialog
         * **/
        @Override
        protected void onPostExecute(String url) {
//             fecha o dialog depois que o arquivo foi baixado
            dismissDialog(progress_bar_type); //está deprecated porem não sei outro comando
            String filePath = Environment.getExternalStorageDirectory().toString() + "/download/bee/bee.apk"; //caminho desejado para o arquivo baixado.
            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent); //abrindo o arquivo .apk baixado
        }
    }

When you run the command:

OutputStream output = new FileOutputStream(caminhoAtt); //aqui ocorre o erro

The following error occurred:

  

/sdcard/download/bee/bee.apk: open failed: ENOENT (No such file or directory)

But I believe the problem is in the download of the file because its length returns -1 as you see in the commented code above.

I would like to know how to make the server not return -1 as content-length in headers

What am I doing wrong?

    
asked by anonymous 13.03.2014 / 18:11

1 answer

1

First we go to the error of -1 being returned by getContentLength() .

getContentLength () returns the header content-length value in the response of your HTTP request. This header may not be included by the server in the response, which causes the method to return this -1 indicating "unknown value".

I'll now cite two possible causes of the error open failed: ENOENT (No such file or directory) , see:

  • Missing the appropriate permission on AndroidManifest.xml :

  • 13.03.2014 / 18:51