-1

This code below works so well on tablets or phones running android 5.1 and below, but 6.0 going up, it does not allow downloading and saving on the storage? what could be the problem, i have tested on 6.0, 6.1 or 7.0 7.1 and 8 but they all don't work.

    class DownloadFile extends AsyncTask<String, Integer, String> {
            @Override
            protected String doInBackground(String... urlParams) {
                int count;
                boolean flag = false;

                try {
                URL url = new URL("http://...");
                URLConnection conexion = url.openConnection();
                conexion.connect();
                // this will be useful so that you can show a tipical 0-100% progress bar
                int lenghtOfFile = conexion.getContentLength();

                // downlod the file
                InputStream input = new BufferedInputStream(url.openStream());
                OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory()+ "/Csentry/CIS.zip");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                publishProgress((int) (total * 100 / lenghtOfFile));
                output.write(data, 0, count);
            }

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

        flag = true;
        }
        catch (Exception e)
        {
        e.printStackTrace();
        }

        return null;

        }
    }
Lucifer
  • 29,392
  • 25
  • 90
  • 143
Bels
  • 85
  • 8

1 Answers1

0

Starting Android 6.0, WRITE_EXTERNAL_STORAGE permission must be requested at runtime. This can be added like this:

if (Build.VERSION.SDK_INT >= 23) {

    if (ContextCompat.checkSelfPermission(AddActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            != PackageManager.PERMISSION_GRANTED) {

       requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_PERMISSION);
    } 
}
Anuraag Baishya
  • 874
  • 2
  • 11
  • 26