0

I am downloading a file from internet in background thread. I declare the permissions and also ask for the persmissions on runtime but still i am getting this exception. I searched a lot about it and all i get is to ask runtime permission and i did so This is my onclick function

    String[] permission ={Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

    if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
            && ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            ActivityCompat.requestPermissions(MainActivity.this, permission, 1);
        }
    } else
    {
        new DownloadFileFromURL().execute(url,name);
    }

This is my async task

    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Resources res =getResources();
            Drawable drawable = res.getDrawable(R.drawable.circular);
            mProgress.setProgress(0);   // Main Progress
            mProgress.setSecondaryProgress(100); // Secondary Progress
            mProgress.setMax(100); // Maximum Progress
            mProgress.setProgressDrawable(drawable);
        }

        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                String name= f_url[1];
                URLConnection conection = url.openConnection();
                conection.connect();

                int lenghtOfFile = conection.getContentLength();
                InputStream input = new BufferedInputStream(url.openStream(),
                        8192);
                OutputStream output = new FileOutputStream(Environment
                        .getExternalStorageDirectory().toString()
                        + name+".apk");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    output.write(data, 0, count);
                }

                output.flush();

                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        protected void onProgressUpdate(final String... progress) {

            new Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    while (pStatus < 100) {
                        pStatus = Integer.parseInt(progress[0]);

                        handler.post(new Runnable() {

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                                mProgress.setProgress(pStatus);
                                tv.setText(pStatus + "%");

                            }
                        });
                    }
                }
            }).start();
        }


        @Override
        protected void onPostExecute(String file_url) {

        }

    }

I think there is some there is some other issue i have declared read externel and write externel storage in manifest too

twana eng
  • 31
  • 10
  • I strongly recommend that you replace all of your `Log.e("Error: ", e.getMessage());` with `Log.e("TwanaApp", "Exception doing ...", e);`, where you replace the `...` with something descriptive. In particular, passing the plain `Exception` into `Log.e()` means that you will get a complete stack trace of where the problem occurs and what the problem is. That information will help you determine if the problem lies in your file access, your network access, or somewhere else. – CommonsWare Apr 04 '20 at 12:54
  • let me do.. and wait i will tell u 1 min – twana eng Apr 04 '20 at 12:56
  • Bear in mind that you do not have access to your desired location on Android 10+, regardless of permissions. Even on older devices, you should replace `OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().toString()+ name+".apk");` with `OutputStream output = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), name+".apk"));`, so you do not make any assumptions about the value of `getExternalStorageDirectory()`. – CommonsWare Apr 04 '20 at 12:56
  • what should i replace `...` in code . how do i know whats going on in code . – twana eng Apr 04 '20 at 12:57
  • so what should i do for downloading file – twana eng Apr 04 '20 at 12:58
  • give me a better a reliable solution that should work on android 10.0 devices too – twana eng Apr 04 '20 at 12:58
  • If you use `getExternalFilesDir(null)` on a `Context` (such as an `Activity`), you will get a directory that you can write to. It works on Android 4.4+ and you do not need any permissions. – CommonsWare Apr 04 '20 at 13:03
  • and one thing more i changed the code of output stream and my app get hang and says `The application may be doing too much work on its main thread` – twana eng Apr 04 '20 at 13:04
  • Does this answer your question? [Exception 'open failed: EACCES (Permission denied)' on Android](https://stackoverflow.com/questions/8854359/exception-open-failed-eacces-permission-denied-on-android) – Santanu Sur Apr 04 '20 at 13:23

1 Answers1

0

you should replace

OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().toString()+ name+".apk");

Write this in your code

OutputStream output = new FileOutputStream(new File(Environment.getExternalStorageDirectory(), name+".apk"));