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

Asked

Viewed 1,035 times

0

I have an Android application, I’m trying to download a .apk and then open it when the download is finished, 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;
        }

That’s another part of the code I haven’t tested yet:

        /**
         * 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 executing the command:

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

The following error occurs:

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

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

I wonder how to make the server not return -1 as content-length in headers

What I’m doing wrong?

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

1 answer

1

First let’s go to the error of -1 being returned by getContentLength().

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

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

  1. Lack of appropriate permission on AndroidManifest.xml:

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

  2. Incorrect file path: For example, instead of /sdcard/download/bee/bee.apk would not be /mnt/sdcard/download/bee/bee.apk ? In any case, the most correct is not to use values hard-coded and yes that way:

    String camioAtt = Environment.getExternalStorageDirectory() + "/download/Bee/Bee.apk";

Obs.: To be more "cri-cri/cri/boring" still, use File.separator instead of "/", but sincerely the day that Android ceases to be Linux-based or else the encoding standard swap character encoding/, you can drop programming the world will be ending... :)

  • Okay, this helped me a little to better understand all this, but did not solve my problem unfortunately. I’m trying everything here if I find solution I warn you

  • Bah managed using another similar solution, and saw that one of the problems was that the folder "Bee" did not exist and android does not create, rs. But I need one thing to finish, as I do for the server to return me the content-length??

  • @Pauloroberto There is my beach (you can add to tag php to the question, if it is the language server-side which you are using), but think you will need to create a script to serve files.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.