How to download file into Any Storage (SD,OTG,Phone) in Android Devices

July 31, 2020

Download File into Any Storage (SD,OTG,Phone) in android device, we have to follow these steps:

Step 1:

we have to give permission to write or download a file into Storage (SD,OTG,Phone).

  1. Give permission into AndroidManifest.xml.
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Give permission of storage into manifest file

  1. Give permission to write file into SD card using Document File

we have to call intent to open DocumentFile to access SD card which shows like this:

      Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
      intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
      startActivityForResult(intent, 42);

Open Actin sheet of DocumentFile to choose SD Card

  1. When we select SD Card from action sheet, then @override method onActivityResult method call automatically. i.e;
      @Override
      protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
          super.onActivityResult(requestCode, resultCode, data);
          if (resultCode != RESULT_OK)
              return;
          else {
              Uri treeUri = data.getData();
              pickedDir = DocumentFile.fromTreeUri(this, treeUri);
              final int takeFlags = data.getFlags()
                      & (Intent.FLAG_GRANT_READ_URI_PERMISSION
                      | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
              getApplicationContext().getContentResolver().takePersistableUriPermission(treeUri, takeFlags);


          }
      }

@override onActivityResult

  1. Variable pickedDir is the path where user want to create file or Directory.
      pickedDir.createDirectory("New Folder");
      pickedDir.createFile("Image/png", filename);

“Image/png” is mime type of file.

  1. How to Download File and save into SD card using DocumentFile
    URL url = new URL("https://dummyimage.com/300.png/09f/fff);
    Uri u = Uri.parse("https://dummyimage.com/300.png/09f/fff);
    File f = new File("" + u);
    String filename = f.getName();
    URLConnection conection =url.openConnection();
    ((URLConnection) conection).connect();
    int lenghtOfFile = conection.getContentLength();
    InputStream input = new BufferedInputStream(
            url.openStream(), 8192);
    DocumentFile ff = pickedDir.createFile("Image/png", filename);
    OutputStream output = getApplicationContext().getContentResolver().openOutputStream(ff.getUri(),"w");
    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();

Written by Manoj Bhardwaj who lives and works in Dharamshala Himachal Pradesh (India). My stackoverflow